"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
↻
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.
Critical Pitfall: Forgetting to update the variable leads to an infinite loop - the program never stops!
When to Use While Loops
"While loops are best for repeating an indefinite number of times - when you don't know how long it's going to 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
Mental Model: A while loop is like a security guard checking your ID. As long as the condition is True, they let you pass through again. Once it's False, the loop stops.
[##################............] 09/15
> [WHY_IT_MATTERS]:
Doing it once is human. Doing it a billion times is machine. Loops leverage the machine's patience.