Source: Aleksandr Popov on Unsplash
for
loops are used to iterate over a sequence (like a list, tuple, or string). Each time through the loop, a variable takes on the value of the next item in the sequence.
nums = [1, 2, 3, 4, 5]
for num in nums:
print(num)
Output:
1
2
3
4
5
break
and continue
are used to control the flow within a loop.
break
immediately exits the loop.continue
skips the rest of the current iteration and moves to the next.
nums = [1, 2, 3, 4, 5]
for num in nums:
if num == 3:
print("Found it!")
break
print(num)
Output:
1
2
Found it!
nums = [1, 2, 3, 4, 5]
for num in nums:
if num == 3:
print("Found it!")
continue
print(num)
Output:
1
2
Found it!
4
5
Nested loops occur when one loop is placed inside another. The inner loop executes completely for each iteration of the outer loop.
nums = [1, 2, 3, 4, 5]
for num in nums:
for letter in 'abc':
print(num, letter)
Output:
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
4 a
4 b
4 c
5 a
5 b
5 c
The range()
function is useful for iterating a specific number of times.
for i in range(10):
print(i)
Output:
0
1
2
3
4
5
6
7
8
9
You can also specify a start and end value:
for i in range(1, 11):
print(i)
Output:
1
2
3
4
5
6
7
8
9
10
while
loops continue to execute as long as a specified condition is true.
x = 0
while x < 10:
print(x)
x += 1
Output:
0
1
2
3
4
5
6
7
8
9
x = 0
while x < 10:
print(x)
if x == 5:
break
x += 1
Output:
0
1
2
3
4
5
x = 0
while True:
print(x)
if x == 5:
break
x += 1
Output:
0
1
2
3
4
5
Caution: Ensure your while True
loops have a break
condition to avoid infinite loops.