1.12 While Loops in Python_older_checkoutlater
 
While Loop Explorer

🔁 While Loop Explorer

Learn how while loops repeat actions until a condition is false!

📚 What is a While Loop?

A while loop repeats a block of code as long as a condition is TRUE. Think of it like following directions: "Keep walking while the path continues." You keep going until the path ends (condition becomes FALSE).

🔧 Parts of a While Loop

1️⃣ Condition

The test that determines if the loop continues

2️⃣ Loop Body

The code that runs each time through the loop

3️⃣ Update

Changes that bring you closer to ending the loop

4️⃣ Exit

When the condition becomes FALSE, the loop stops

💻 While Loop Syntax

while condition:
    # Code to repeat
    # This runs while condition is True
    # Don't forget to update the condition!

Example:

count = 0
while count < 5:
    print(count)
    count = count + 1
# Output: 0, 1, 2, 3, 4

🎮 Interactive Demo: Counter Loop

Ready to run! Click the button above.

🎯 Interactive Demo: Pattern Builder

Click to build a pattern!

⚠️ Warning: Infinite Loops!

If the condition never becomes FALSE, the loop runs forever! Always make sure your loop has a way to end. Example of an infinite loop: while True: print("Forever!")

🏃 Karel Example: Move to Wall

# Karel keeps moving until hitting a wall
while front_is_clear():
    move()
# Loop stops when Karel reaches the wall

This loop lets Karel move forward until there's a wall. The condition front_is_clear() checks before each move!

Last updated  2026/03/24 16:16:16 PDTHits  35