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)
You can browse a string character by character:
for x in "Peugeot":
print(x)
With the break statement you can stop the for.
cars = ["Renault", "Peugeot", "BMW"]
for x in cars:
print(x)
if x == "Peugeot":
break
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
for x in range(4, 8):
print(x)
for x in range(8):
print(x)
else:
print("the for loop is complete")
rows=["1", "2", "3"]
columns = ["4", "5", "6"]
for x in rows:
for y in columns:
print(x, y)
Please disable your ad blocker and refresh the window to use this website.