Python For Loops
Python For Loops
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
O/P:
apple
banana
cherry
Example
for x in "banana":
print(x)
O/P:
b
a
n
a
n
a
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
O/P:
apple
banana
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
O/P
apple
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
O/P:
apple
cherry
Example
for x in range(6):
print(x)
O/P:
0
1
2
3
4
5
Example
for x in range(2, 6):
print(x)
O/P:
2
3
4
5
The range() function defaults to increment the sequence by 1, however it is
possible to specify the increment value by adding a third parameter: range(2,
30, 3):
Example
for x in range(2, 30, 3):
print(x)
O/P:
2
5
8
11
14
17
20
23
26
29
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
O/P:
0
1
2
3
4
5
Finally finished!
Note: The else block will NOT be executed if the loop is stopped by
a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
O/P:
0
1
2
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
O/P:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Example
for x in [0, 1, 2]:
pass
# having an empty for loop like this, would raise an error without the pass statement