Python - For Loop
To iterate repeatedly through a sequence, use a for loop (that is, a list, tuple, dictionary, set, or string).
This works more like an iterative method seen in other object-oriented programming languages and is less like the for keyword found in other programming languages.
The for loop allows us to execute a series of statements once for each item in a list, tuple, set, etc.
cars = ["Renault", "Peugeot", "BMW"]
for x in cars:
print(x)
Browse a string
You can browse a string character by character:
for x in "Peugeot":
print(x)
The break statement in a for
With the break statement you can stop the for.
cars = ["Renault", "Peugeot", "BMW"]
for x in cars:
print(x)
if x == "Peugeot":
break
The statement continues in a for
With the continue instruction we can stop the current iteration and move on to the next element.
cars = ["Renault", "Peugeot", "BMW"]
for x in voitures:
print(x)
if x == "Peugeot":
continue
The range()
The range() function allows us to iterate through a set of code a predetermined number of times.
The range() function returns a series of numbers that, by default, starts at 0 and increments by 1 before stopping at a predetermined value.
for x in range(4, 8):
print(x)
The initial value of the range() function is 0 by default, but a starting value can be specified by adding a parameter: range(4, 8), which indicates values from 4 to 6 (but excluding 8:
Else in a for
else loop is used to specify the block of statements that will be executed once the for loop is complete.
for x in range(8):
print(x)
else:
print("the for loop is complete")
Note: The instruction block in else does not execute if you add a break in the for loop.
Nested for loop
A nested for loop is a loop inside another for loop. It's perfect for traversing a matrix for example:
rows=["1", "2", "3"]
columns = ["4", "5", "6"]
for x in rows:
for y in columns:
print(x, y)