🔄 Quick Recap (Day 6)

  • You learned to make decisions with if, elif, and else.

  • You handled user input and used comparisons to branch logic.

🎯 What You’ll Learn Today

  1. How for loops iterate over sequences.

  2. How while loops repeat while a condition holds.

  3. How to use break to exit a loop early.

  4. How to use continue to skip to the next iteration.

📖 Overview: for Loops

A for loop repeats a block of code for each item in a sequence (list, string, range):

# Loop through a list of fruits
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry
  • fruit is a variable that takes each value from fruits in turn.

  • Indentation shows the block that repeats.

Using range()

To loop a specific number of times:

for i in range(5):  # 0,1,2,3,4
    print(i)

Output:

0
1
2
3
4

📖 Overview: while Loops

A while loop repeats as long as a condition is true:

count = 0
while count < 3:
    print("Count is", count)
    count += 1

Output:

Count is 0
Count is 1
Count is 2

Be careful: if the condition never becomes false, the loop runs forever. Always update a variable inside the loop.

📖 Controlling Loops: break and continue

  • break immediately exits the loop:

    for num in range(10):
        if num == 3:
            break
        print(num)

    Output:

    0
    1
    2
  • continue skips to the next iteration:

    for num in range(5):
        if num % 2 == 0:
            continue
        print(num)

    Output:

    1
    3

🧙‍♂️ Take the Wand and Try Yourself

  1. Create a file named loop_practice.py.

  2. Write a for loop that prints the square of numbers 1 through 5.

  3. Write a while loop that starts at 5 and counts down to 1.

  4. Inside the for loop, use continue to skip printing when the square is divisible by 4.

  5. Inside the while loop, use break if the count reaches 2.

Solution Example (loop_practice.py):

# loop_practice.py
# For loop with continue
for i in range(1, 6):
    square = i * i
    if square % 4 == 0:
        continue
    print("Square of", i, "is", square)

# While loop with break
count = 5
while count >= 1:
    if count == 2:
        break
    print("Counting down:", count)
    count -= 1

Run:

python loop_practice.py

Expected output:

Square of 1 is 1
Square of 3 is 9
Square of 5 is 25
Counting down: 5
Counting down: 4
Counting down: 3

Once you see this output, you’ve mastered loops and their controls!

On Day 8: Lists, we’ll explore how to work with collections of data. See you there!

Keep Reading