Repeating Actions

🔄 Don't Repeat Yourself: Let the Computer Do the Work

Master the art of repetition: for known iterations, while for conditions

🧠 Mental Model: Loops as Automation

The Perfect Metaphor: Assembly Line Worker

Think of loops as an assembly line worker who performs the same task repeatedly. The key question is: How does the worker know when to stop?

  • for loop - "I have exactly 10 items to process" (known count)
  • while loop - "I'll keep working until the whistle blows" (condition-based)

🔢 for Loop

Like following a recipe with numbered steps

Step 1 → Step 2 → Step 3 → Done!

Use when you know how many times to repeat

🔄 while Loop

Like a guard who stays on duty until relieved

Check condition → Act → Check again...

Use when you're waiting for something to become true/false

🔢 for Loops: When You Know the Count

Use for loops when you know in advance how many times you want to repeat something. Think "for each item in this collection" or "for each number from 1 to 10."

Interactive for Loop Explorer

The most common pattern: for i in range(n) - repeat n times

# Count from 0 to 4 (5 times total)
for i in range(5):
    print(f"Step {i + 1}: Hello!")
    
# Output:
# Step 1: Hello!
# Step 2: Hello!
# Step 3: Hello!
# Step 4: Hello!
# Step 5: Hello!
Enter a count and click 'Run for Loop'

🧠 Understanding range()

range(5)
0, 1, 2, 3, 4
5 numbers, starts at 0
range(2, 6)
2, 3, 4, 5
From 2 to 6 (exclusive)
range(0, 10, 2)
0, 2, 4, 6, 8
Step by 2

🔄 while Loops: When You Wait for a Condition

Use while loops when you don't know exactly how many times you'll need to repeat, but you know what condition needs to be met to stop.

Interactive while Loop: Guessing Game

Perfect example: keep asking for guesses until the user gets it right

secret_number = 7
guess = 0

while guess != secret_number:
    print("Guess the number (1-10)")
    guess = int(input())  # User enters a guess
    
    if guess != secret_number:
        print("Try again!")

print("You got it!")

Guess the secret number (1-10):

Start guessing!

⚠️ Critical Danger: Infinite Loops

The #1 while loop mistake: forgetting to change the condition variable inside the loop. This creates an infinite loop that never stops!

❌ Infinite Loop!

count = 0
while count < 5:
    print("Hello")
    # OOPS! count never changes!
    # This will run forever!

✅ Correct Version

count = 0
while count < 5:
    print("Hello")
    count += 1  # Change the variable!
    # Now it will stop when count reaches 5

🛑 Loop Control: break and continue

Sometimes you need to modify how a loop behaves. Python provides two keywords for loop control:

🛑 break

"Stop the loop immediately and exit"

for i in range(10):
    if i == 5:
        break  # Stop when i is 5
    print(i)
# Prints: 0, 1, 2, 3, 4

⏭️ continue

"Skip this iteration and go to the next one"

for i in range(5):
    if i == 2:
        continue  # Skip when i is 2
    print(i)
# Prints: 0, 1, 3, 4

Interactive break vs continue Demo

Click a demo button to see loop control in action

🎯 Mastery Check: Loops & Repetition

Question 1: Choosing the Right Loop

You want to print "Hello" exactly 5 times. Which loop is most appropriate?

for i in range(5):

while True:

while i < 5: (without initializing i)

Question 2: Infinite Loop Detection

Which of these creates an infinite loop?

x = 1
while x < 10:
    print(x)
    # What's missing here?

This code is fine as written

This creates an infinite loop because x never changes

This will stop after printing x once

🎯 Ready for Collections!

What You've Mastered

  • ✅ for loops for known iterations (range, sequences)
  • ✅ while loops for condition-based repetition
  • ✅ How to avoid infinite loops (always change the condition!)
  • ✅ Loop control with break and continue
  • ✅ When to use each type of loop

Now that you can repeat actions, let's learn about storing and processing collections of data with lists!

Continue to Collections of Data →