For in Python
Here’s the Python translation of the Go “For” example, formatted in Markdown suitable for Hugo:
Python offers several ways to create loops, with the for
loop being the most common. Let’s explore different types of for
loops in Python.
# The most basic type, using a range
for i in range(1, 4):
print(i)
# Using enumerate to get both index and value
for i, value in enumerate(range(3)):
print(i)
# Iterating over a sequence (in this case, a string)
for char in "abc":
print(f"range {char}")
# An infinite loop (be careful with these!)
while True:
print("loop")
break # This will exit the loop after one iteration
# Using continue to skip iterations
for n in range(6):
if n % 2 == 0:
continue
print(n)
When you run this program, you’ll see:
$ python for_loops.py
1
2
3
0
1
2
range a
range b
range c
loop
1
3
5
Python’s for
loop is quite versatile. It can iterate over any sequence (list, tuple, dictionary, set, or string) or other iterable objects. The range()
function is commonly used to generate a sequence of numbers.
The while
loop in Python is equivalent to the condition-only for
loop in some other languages. It will continue looping until the condition becomes false or a break
statement is encountered.
The continue
statement is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
We’ll see some other forms of iteration later when we look at list comprehensions, generators, and other data structures.