"Problem: Repeating actions require you to copy and paste the same line multiple times.
Solution: We can repeat something using a structure called a loop."
The Problem of Repetition
# Without loops - tedious and error-prone
print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")
# What if we need 100 times? 1000 times?
While Loop: The Repeating If Statement
WHILE condition is True: Keep executing this block & boomerang back!
↻
Think: "Keep doing this AS LONG AS the condition is True"
Key Insight: While loop checks the condition BEFORE each repetition. If condition becomes False, loop stops.
Interactive While Loop
Click 'Run While Loop' or 'Step Through' to begin
Output will appear here...
PITFALL WATCHAnatomy of a While Loop & The Infinite Loop Trap+ Explore
Critical Pitfall: Forgetting Step 4 (updating the checked variable) leads to an infinite loop — the condition stays True forever!
CODE EXAMPLESWhen to Use While Loops (Passwords & Game Loops)+ Explore
"While loops are best for repeating an indefinite number of times — when you don't know ahead of time how many tries it will take."
# Good use case: Keep asking until valid input
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")
# Another good use: Game loop
game_running = True
while game_running:
play_turn()
if player_won():
game_running = False
Woodland Milestone: You've tamed the boomerang of while loops! Next, let's see how for loops and range() make counted repetition effortless.