While Loops Slides
Computing Foundations Python Unit • Week 4
45-Minute Lesson
While Loops: Making Our Programs Smarter
From “Play 5 Rounds” to “Play Until Someone Wins”
Learning Targets
Explain how a while loop controls repetition.
Choose between a for loop and a while loop.
Explain how break and continue alter loops.
Identify sequence, selection, and iteration.
Building on Rock, Paper, Scissors Slide 1 of 25
Warm-Up Analysis Start With What We Already Built
Slide 2 of 25
rps_v1.py
Our Current Game
player_score = 0
computer_score = 0
for i in range(5):
# play one round
# update scores
Examine This Code
1. What does range(5) tell Python to do?
Think about the exact number of cycles Python prepares.
2. How many rounds will this game always play?
Can this code stop at Round 3 on its own?
3. Is that how a real best-of-five match works?
What happens if someone sweeps 3-0?
Pause for classroom discussion before advancing Do not reveal answers yet!
Logic Flaw The Problem with Fixed Repetition
Slide 3 of 25
A Best-of-Five Match Ends at 3 Wins!
If the player wins Round 1, Round 2, and Round 3, the match is over! Playing Rounds 4 and 5 is unnecessary and unrealistic.
Current Code: Blind Repetition
for i in range(5) counts blindly to five. It doesn't care who is winning or if the match was already won.
What We Actually Need
We need Python to check the game state after every round and stop as soon as either player reaches 3 wins.
How could we tell Python to keep playing UNTIL someone reaches 3 wins?
We need a new kind of loop! Slide 3 of 25
New Python Keyword Introducing the While Loop
Slide 4 of 25
Formal Definition
A while loop repeats code as long as a condition remains True.
Our New RPS Loop Header:
while player_score < 3 and computer_score < 3:
Plain English Translation
"While the player has fewer than 3 wins AND the computer has fewer than 3 wins, keep playing another round."
When Does It Stop?
The loop stops immediately at the moment its condition evaluates to False.
Repetition is now governed by game rules, not an arbitrary counter Slide 4 of 25
Core Comparison for Loop vs. while Loop
Slide 5 of 25
for loop
Definite
for i in range(5):
Meaning: Repeat a known number of times.
When to use: When you already know upfront how many repetitions are required.
Rule of Thumb: for = Known Repetition
while loop
Conditional
while p_score < 3 and c_score < 3:
Meaning: Repeat as long as a condition is True.
When to use: When you do not know how many repetitions will be needed.
Rule of Thumb: while = Condition-Controlled
for = count-controlled • while = condition-controlled
Rock, Paper, Scissors ties make the round count unpredictable Slide 5 of 25
Program Tracing Trace Case 1: Game Continues
Slide 6 of 25
Player Score 2
vs
Computer Score 1
Evaluating: while player_score < 3 and computer_score < 3:
player_score < 3 2 < 3 True
AND
computer_score < 3 1 < 3 True
Result: True and True = True
Neither player has reached 3 wins yet. Python enters the loop to play another round!
PLAY ROUND
Both sub-conditions must be True for the and logical operator to yield True Slide 6 of 25
Program Tracing Trace Case 2: Game Stops
Slide 7 of 25
Player Score (just won round!) 3
vs
Computer Score 1
Evaluating: while player_score < 3 and computer_score < 3:
player_score < 3 3 < 3 False
AND
computer_score < 3 1 < 3 True
Result: False and True = False
The while condition evaluated to False! The loop exits immediately.
EXIT LOOP
As soon as any side hits 3 wins, False and ... becomes False Slide 7 of 25
Live Code-Along Upgrade Your Colab Notebook
Slide 8 of 25
Open your multi-round Rock, Paper, Scissors notebook in Google Colab.
1 FIND THIS LINE:
for i in range(5):
2 REPLACE IT WITH THIS LINE:
while player_score < 3 and computer_score < 3:
Key Reminder: Do NOT rewrite round logic! Only swapping the loop controller.
Run & Test!
Test your code by playing through at least one full match Slide 8 of 25
Reflection What Changed in Our Game?
Slide 9 of 25
Notice how your game behaves now:
Dynamic Length
Does every game last the same number of rounds? No! Games can end in 3, 4, 5, or even 7+ rounds.
Early Finish
Can a match end after only 3 scored rounds? Yes! If someone sweeps 3-0, Python stops immediately.
Tie Handling
Can a game last longer than 5 rounds? Yes! Ties don't award points, so the game keeps going until 3 wins.
State-Aware
What causes the loop to stop? The game state! Either player_score == 3 or computer_score == 3.
The program reacts to the STATE of the game rather than blindly repeating five times!
Our code just got significantly smarter Slide 9 of 25
Big Ideas The Three Fundamental Structures
Slide 10 of 25
Every computer program ever written is built from combinations of these three structures:
Sequence
ORDER
Instructions execute line-by-line, top to bottom.
1. Init scores
2. Get input
3. Print result
"Do this, then do that"
Selection
DECISIONS
Choose which path to take based on a condition.
if condition:
elif other:
else:
"If this is true, do this"
Iteration
REPETITION
Repeat a block of instructions multiple times.
for i in range():
while condition:
"Keep doing this"
Key Takeaway: Our single RPS program uses all three structures working together!
Remember these three terms: Assessment key concepts! Slide 10 of 25
Code Spotting Find the Three Structures in RPS
Slide 11 of 25
// 1. SEQUENCE (Setup)
player_score = 0
computer_score = 0
// 2. ITERATION (Game Loop)
while player_score < 3 and computer_score < 3:
player = input("Choose r/p/s: ")
// 3. SELECTION (Decision)
if player == computer:
print("Tie!")
elif player == "rock" and computer == "scissors":
print("Win!"); player_score += 1
else:
print("Lose!"); computer_score += 1
Can You Spot All Three?
1
Sequence
Score setup runs before the loop begins.
2
Iteration
while repeats until someone gets 3 wins.
3
Selection
if / elif / else decides who scored.
Notice how selection lives INSIDE the iteration block! Slide 11 of 25
Common Pitfall A New Problem: Infinite Loops
Slide 12 of 25
What is wrong with this code? bug.py
score = 0
while score < 3:
print(score)
Output: 0 0 0 0 0 0 0 0 0 ... (never ends!)
The Definition
Infinite Loop:
A loop that never reaches a condition that causes it to stop.
Why Does This Happen Here?
- •
score starts at 0.
- • Nothing inside the loop ever changes
score.
- • Therefore,
0 < 3 is ALWAYS True!
In Colab, you would need to press the Stop button to interrupt this! Slide 12 of 25
Fixing Bugs Preventing Infinite Loops
Slide 13 of 25
The Fixed Code fixed.py
score = 0
while score < 3:
print(score)
score += 1 # Changes state!
Output: 0 1 2 (stops cleanly!)
Trace the Progression
Loop 1score = 0
→
Loop 2score = 1
→
Loop 3score = 2
→
Checkscore = 3
When score reaches 3, 3 < 3 becomes False!
The Golden Rule of While Loops
Something must change inside the loop so that the stopping condition can eventually be reached!
In our RPS game, player_score += 1 changes the state towards 3 Slide 13 of 25
Loop Control Another Way Out: break
Slide 14 of 25
Keyword Definition
break immediately exits the entire loop.
quit_pattern.py Emergency Exit
while True:
answer = input("Type quit to stop: ")
if answer == "quit":
break
print("Loop ended successfully!")
How This Works:
while True would normally repeat forever.
break gives the program an emergency door out!
- Python instantly jumps to the code below the loop.
break abandons the loop completely and moves forward Slide 14 of 25
Practical Applications Why Would We Use break?
Slide 15 of 25
Common Real-World Programming Use Cases:
Stop a Game Early
If the player health hits 0, or if they press "Pause / Quit", break out immediately.
Exit an App Menu
Keep displaying choices until user selects option "9: Exit".
Guessing Game Victory
Loop forever until the player guesses the secret number, then break!
Data Entry Done
Collect student names until the teacher types "done" or blank input.
Core Idea: break ends the loop completely right where it stands.
Next, let's explore a loop controller that skips instead of quitting Slide 15 of 25
Loop Control Skip This Turn: continue
Slide 16 of 25
Keyword Definition
continue skips the rest of the current cycle and goes right to the next repetition.
skip_two.py Skip Turn
for i in range(5):
if i == 2:
continue
print(i)
What Prints?
0 1 2 3 4
When i == 2, Python hit continue. It skipped print(2) and jumped immediately to i = 3!
The loop did NOT stop! It only skipped round 2. Slide 16 of 25
Visual Comparison break vs. continue
Slide 17 of 25
break
The Stop Sign
"LEAVE THE ENTIRE LOOP"
Eject from the loop completely. Never run any remaining repetitions. Move directly to the line after the loop.
Loop is over for good!
continue
The Skip Button
"SKIP TO NEXT REPETITION"
Abandon only the rest of this current round. Jump immediately back to the top of the loop to check the condition again.
Loop keeps going!
break = Eject button • continue = Fast-forward to next turn Slide 17 of 25
Optional Upgrade Apply continue to RPS Input Validation
Slide 18 of 25
Problem: What if a player types typos or nonsense?
If the player enters "banana", your old game might score it as a tie or computer win!
Add this right after asking for player input:
player = input("Choose rock, paper, or scissors: ")
if player not in ["rock", "paper", "scissors"]:
print("Invalid choice! Try again.")
continue # Skips scoring, loops back!
Why it works: continue restarts the loop immediately without awarding any points!
Spicy Upgrade
Add this to your notebook if you have time during the code-along Slide 18 of 25
Independent / Pair Work Code-Along Challenge Checklist
Slide 19 of 25
Your Colab RPS Mission:
10 Minutes Testing Time
✓
Uses a while loop instead of for i in range(5)
✓
Stops as soon as either player or computer reaches 3 wins
✓
Keeps score accurately after each round (ties award 0 points)
✓
Announces the final match champion AFTER the loop concludes
★
Extra Challenge: Add invalid-input handling using continue
Test your game at least twice with a classmate! Slide 19 of 25
Code Reading Practice 1: Trace the While Loop
Slide 20 of 25
predict_1.py Trace Carefully
count = 1
while count < 4:
print(count)
count += 1
Predict These 3 Questions:
1. What exact numbers will print?
Does it print 4? Why or why not?
2. How many total repetitions occur?
Count each time the loop body runs.
3. What causes the loop to stop?
What is the value of count when it exits?
Turn and talk to your neighbor before answering Prints: 1, 2, 3 (stops when count becomes 4)
Code Reading Practice 2: Predict break
Slide 21 of 25
predict_break.py Watch the Order!
count = 0
while True:
count += 1
if count == 3:
break
print(count)
What will print to the screen?
Trace line by line:
• count starts at 0
• count becomes 1 → print(1)
• count becomes 2 → print(2)
• count becomes 3 → break!
Does print(3) ever execute?
No! The loop exits on the break before reaching the print statement.
Order inside the loop matters enormously! Prints only: 1 and 2
Code Reading Practice 3: Predict continue
Slide 22 of 25
predict_continue.py What Skips?
for i in range(5):
if i == 3:
continue
print(i)
What values will print?
Remember: range(5) generates:
[ 0, 1, 2, 3, 4 ]
Which element gets intercepted by the continue statement?
Only 3 is skipped! The loop keeps going for 4.
Turn and check with a partner Output: 0, 1, 2, 4
Review Matrix Unit Mastery Review Chart
Slide 23 of 25
Concept 1
Sequence
Order
Instructions happen step-by-step from top to bottom.
x = 0
print(x)
Concept 2
Selection
Decisions
The program chooses what to do based on condition.
if / elif / else
Concept 3
Iteration
Repetition
The program repeats code automatically.
for / while
Control
Overrides
Loop Flow
Special commands to change loop behavior.
break = leave
continue = skip
You will need to explain and recognize these structures on your upcoming assessment Slide 23 of 25
Programmer Mindset Why This Matters
Slide 24 of 25
Programming is not just memorizing commands.
Software engineers choose structures intentionally based on the exact problem they want to solve:
"I know exactly how many repetitions I need." → for
"I want to repeat until something changes." → while
"I want the program to choose between possibilities." → selection
"I need to stop a loop immediately." → break
"I need to skip one repetition and continue." → continue
You have all the core control structures of computer science! Slide 24 of 25
Check for Understanding Exit Ticket
Slide 25 of 25
Answer on your sheet or digital form:
Final 5 Minutes
1. What does a while loop do?
Explain the role of the condition.
2. for vs. while?
What is the key difference in when you use them?
3. What causes an infinite loop?
Why does it fail to terminate?
4 & 5. break vs. continue?
What does break do? What does continue do?
6. Which programming structure do loops represent?
Sequence • Selection • Iteration
7. Why is a while loop better for best-of-5 RPS than for i in range(5)?
Connect your answer to game rules and tie rounds.
Computing Foundations • Great job today! Completed