Data Structures
Python Loops, Break, Continue, and Range: Part 7
A detailed explanation of loops in Python, essential for controlling the flow of your programs and repeating actions.
Ryan McBride
Ryan McBride
alt

Source: Aleksandr Popov on Unsplash

1. For Loops

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
   

2. Break and Continue Keywords

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.

Break Example:


nums = [1, 2, 3, 4, 5]
for num in nums:
    if num == 3:
        print("Found it!")
        break
    print(num)
   

Output:


1
2
Found it!
   

Continue Example:


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
   

3. Nested Loops

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
   

4. Range Function

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
   

5. While Loops

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
   

While Loop with Break:


x = 0
while x < 10:
    print(x)
    if x == 5:
        break
    x += 1
   

Output:


0
1
2
3
4
5
   

Infinite While Loop (with Break):


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.