1.5 Hours

6. Loops & Iteration

Module 06: Loops & Iteration

The superpower of automation

What if you needed to print the numbers 1 to 1,000? Without loops, you'd write 1,000 print() statements. With a loop, you write two lines. Loops are the mechanism by which computers do what they're built for: repeat things with incredible speed and perfect accuracy.

Every time you've used an app, seen a news feed, or run a search — loops were working behind the scenes, processing every item in a list, every row in a database, every pixel in an image.

for Loops

Loop Lifecycle: For & While Mechanics 1. INITIALIZE i = 0 2. CHECK i < 5? TRUE 3. RUN BODY print(f'Item {i}') 4. STEP i += 1 Repeats cycle until condition evaluates to False FALSE → EXIT LOOP

A for loop runs a block of code once for each item in a sequence — a list, a range of numbers, characters in a string:

Python 3
# Loop through a range of numbers
for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

# Loop through a list
fruits = ['apple', 'mango', 'orange', 'pawpaw']
for fruit in fruits:
    print('I have a ' + fruit)

# Loop with start and end
for num in range(1, 11):
    print(num)  # Prints 1 through 10

# Loop with a step
for even in range(0, 20, 2):
    print(even)  # 0, 2, 4, 6, 8, ... 18

while Loops

A while loop keeps running as long as a condition is True. You use it when you don't know in advance how many times you'll need to loop:

Python 3
# Count down from 10
count = 10
while count > 0:
    print(count)
    count -= 1
print('Liftoff!')

# Keep asking until valid input
answer = ''
while answer != 'yes' and answer != 'no':
    answer = input('Do you agree? (yes/no): ')
print('You chose:', answer)
Infinite Loop Warning

If your while condition never becomes False, your program runs forever. Always make sure something inside the loop will eventually make the condition False.

do-while Loops

Python doesn't have a built-in do-while, but the concept is: run the code once first, then check the condition. You simulate it like this:

Python 3
# Simulating do-while in Python
while True:
    user_input = input('Enter a positive number: ')
    number = int(user_input)
    if number > 0:
        break  # Exit the loop
    print('That is not positive. Try again.')

print(f'You entered: {number}')

In JavaScript, do-while exists natively and guarantees the block runs at least once:

JavaScript
// JavaScript do-while
let num;
do {
    num = parseInt(prompt('Enter a positive number:'));
} while (num <= 0);

Break & Continue

Two keywords give you fine-grained control inside loops:

Python 3
# break — exits the loop immediately
for number in range(1, 100):
    if number == 7:
        break  # Stop as soon as we hit 7
    print(number)  # Prints 1, 2, 3, 4, 5, 6

# continue — skips the rest of this iteration
for number in range(1, 11):
    if number % 2 == 0:
        continue  # Skip even numbers
    print(number)  # Prints 1, 3, 5, 7, 9

Nested Loops

Loops inside loops. For every iteration of the outer loop, the inner loop runs completely:

Python 3
# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f'{i} x {j} = {i*j}')

# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
# 2 x 1 = 2
# ... and so on

Nested loops are used for working with grids, matrices, tables, and combinations. Be mindful: if the outer loop runs n times and the inner loop runs m times, you get n × m total iterations — this can get slow with large data.

Knowledge Check

Ready to test your understanding of 6. Loops & Iteration?

Back