Loops are used to repeatedly execute a block of code. In Python, there are mainly two types of loops:
The for loop in Python is used to iterate over a sequence (list, tuple, dictionary, set, or string) or other iterable objects.
for i in range(5):
print(i)
0
1
2
3
4
range(5) to range(2, 5)?
for i in range(2, 5):
print(i)
2
3
4
The while loop in Python is used to execute a block of code as long as the condition is true.
i = 0
while i < 5:
print(i)
i += 1
0
1
2
3
4
i inside the while loop?
i, the condition i < 5 will always be true, resulting in an infinite loop.
Loops can be nested inside each other. This means you can have a loop inside another loop.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
Python provides various loop control statements to change the loop's execution flow:
break: Terminates the loop statement and transfers execution to the statement immediately following the loop.continue: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.pass: A null statement, used as a placeholder in loops.
for i in range(5):
if i == 3:
break
print(i)
0
1
2
for i in range(5):
if i == 3:
continue
print(i)
0
1
2
4
for i in range(5):
if i == 3:
pass
print(i)
0
1
2
3
4
while loop.
a, b = 0, 1
count = 0
while count < 10:
print(a)
a, b = b, a + b
count += 1
0
1
1
2
3
5
8
13
21
34
for loop to iterate over a dictionary's keys and values?
items() method to get key-value pairs.
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
print(f"{key}: {value}")
a: 1
b: 2
c: 3