A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
#Print each fruit in a fruit list:
marks = [10,20,30,40,50]
for x in marks:
print(x)
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
#Exit the loop when x is 30:
marks = [10,20,30,40,50]
for x in marks:
print(x)
if x == 30:
break
Output:
10
20
30
Example 2:
Exit the loop when x is 30, but this time the break comes before the print:
marks = [10,20,30,40,50]
for x in marks:
if x == 30:
break
print(x)
Output:
10
20
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the next:
#Do not print banana:
marks = [10,20,30,40,50]
for x in marks:
if x == 30:
continue
print(x)
Output:
10
20
40
50
Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop":
Example:1
#Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Example 2:
m1 = [1,2,3]
m2 = [10,20,30]
for x in m1:
for y in m2:
print(x, y)
Output:
(1, 10)
(1, 20)
(1, 30)
(2, 10)
(2, 20)
(2, 30)
(3, 10)
(3, 20)
(3, 30)