The Magic Merry-Go-Round: Python While Loops
Imagine a merry-go-round that keeps spinning until someone says “STOP!” That’s exactly how while loops work in Python!
What is a While Loop?
Think of a while loop like this:
“Keep doing this thing… while this is true.”
It’s like telling your little robot friend:
- “Keep eating cookies while you’re still hungry”
- “Keep running while the music plays”
- “Keep counting while we haven’t reached 10”
count = 1
while count <= 5:
print(count)
count = count + 1
What happens?
1
2
3
4
5
The loop checks: “Is count still 5 or less?” If yes, keep going! Once count becomes 6, the ride stops.
While Loop Basics
The Recipe
Every while loop has three simple parts:
graph TD A["Start with something"] --> B{Check condition} B -->|True| C["Do something"] C --> D["Change something"] D --> B B -->|False| E["Exit loop"]
A Simple Example
Let’s make a countdown like a rocket launch:
countdown = 5
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("BLAST OFF!")
Output:
5
4
3
2
1
BLAST OFF!
The Golden Rule
Always change something inside your loop!
If you forget, your merry-go-round will spin forever!
# BAD - Never ends!
x = 1
while x < 5:
print(x)
# Oops! We forgot: x = x + 1
Break Statement: The Emergency Exit
What is Break?
Imagine you’re on that merry-go-round, and suddenly you see an ice cream truck. You want to jump off immediately!
That’s what break does. It says: “STOP right now! I’m getting off!”
number = 1
while number <= 10:
if number == 5:
print("Found 5! Jumping off!")
break
print(number)
number = number + 1
Output:
1
2
3
4
Found 5! Jumping off!
See? We never reached 10. Once we found 5, we broke out!
Real-Life Example: Finding a Toy
toys = ["car", "ball", "teddy", "robot"]
index = 0
while index < len(toys):
if toys[index] == "teddy":
print("Found my teddy!")
break
print(f"Checking {toys[index]}...")
index = index + 1
Output:
Checking car...
Checking ball...
Found my teddy!
Continue Statement: Skip and Keep Going
What is Continue?
Imagine you’re picking apples. You see a rotten one. Do you stop picking? No! You just skip that apple and keep going.
continue says: “Skip this round, but keep the loop running!”
number = 0
while number < 5:
number = number + 1
if number == 3:
print("Skipping 3!")
continue
print(number)
Output:
1
2
Skipping 3!
4
5
Notice how 3 was skipped, but we kept going to 4 and 5!
The Difference
graph TD A["break"] --> B["Stops entire loop"] C["continue"] --> D["Skips current round only"]
| Command | What it does |
|---|---|
break |
EXIT the whole ride |
continue |
Skip this turn, stay on ride |
Pass Statement: The “Do Nothing” Placeholder
What is Pass?
Sometimes you need to write a loop but haven’t decided what goes inside yet. It’s like saving a seat for a friend who isn’t here yet.
pass says: “I’m here, but I’ll do nothing for now.”
count = 0
while count < 3:
count = count + 1
pass # TODO: Add code later
This runs without errors, even though we’re not doing anything useful yet!
When to Use Pass
- Planning your code structure
- Creating placeholder loops
- When syntax requires something but you’re not ready
# Placeholder for future logic
while True:
pass # Will add game logic later
Note: Using pass in a while True loop creates an infinite loop that does nothing. Only use this as a temporary placeholder!
Assignment Expressions: The Walrus Operator
What is It?
Python 3.8 introduced a cool trick called the walrus operator :=
It looks like a walrus! → := (two eyes and tusks!)
It lets you assign and check at the same time.
Before (The Old Way)
line = input("Type something: ")
while line != "quit":
print(f"You said: {line}")
line = input("Type something: ")
We had to write input() twice!
After (The Walrus Way)
while (line := input("Type: ")) != "quit":
print(f"You said: {line}")
One line does two jobs:
- Gets input and stores it in
line - Checks if it equals “quit”
Another Example
Reading numbers until we get 0:
while (num := int(input("Number: "))) != 0:
print(f"Square is {num * num}")
print("Done!")
The := assigns and returns the value at the same time. Magic!
Loop Else Clause: The “Finish Line” Prize
What is Loop Else?
This is Python’s special superpower! A while loop can have an else block.
The else runs only if the loop finished normally (without a break).
Think of it like a marathon:
- If you finish the race → You get a medal (else runs)
- If you quit early → No medal (else skips)
Example: Searching for a Number
target = 7
current = 1
while current <= 5:
if current == target:
print("Found it!")
break
current = current + 1
else:
print("Not found in range")
Output:
Not found in range
Since we never found 7, we finished normally, so else ran!
When Break Is Used
target = 3
current = 1
while current <= 5:
if current == target:
print("Found it!")
break
current = current + 1
else:
print("Not found")
Output:
Found it!
The else didn’t run because we used break!
Summary Table
| What happened | Does else run? |
|---|---|
| Loop ended normally | YES |
| Loop was broken | NO |
Putting It All Together
Let’s build a simple guessing game using everything we learned:
secret = 7
guess = 0
while (guess := int(input("Guess: "))) != secret:
if guess == 0:
print("Giving up!")
break
elif guess < secret:
print("Too low!")
continue
else:
print("Too high!")
else:
print("You got it!")
What’s happening:
:=assigns and checks the guessbreakexits if player gives upcontinueskips to next guesselsecelebrates when found!
Quick Reference
graph TD A["while condition:"] --> B{Is condition true?} B -->|Yes| C["Run loop body"] C --> D{Hit break?} D -->|Yes| E["Exit - NO else"] D -->|No| F{Hit continue?} F -->|Yes| B F -->|No| G["Finish body"] G --> B B -->|No| H["Run else if exists"] H --> I["Exit loop"]
| Keyword | What it does |
|---|---|
while |
Keep going while true |
break |
Exit immediately |
continue |
Skip to next round |
pass |
Do nothing (placeholder) |
:= |
Assign and use together |
else |
Run if no break |
You Did It!
You now understand the complete magic of Python while loops! You know:
- How while loops repeat code
- How to escape with
break - How to skip with
continue - How to hold space with
pass - How to be clever with
:= - How to reward completion with
else
The merry-go-round of learning never stops, but now you control it!
