Python Wrap Up Slides
Computing Foundations • Final Python Lesson
Python Wrap-Up
While Loops + Sequence, Selection, and Iteration
Today's Learning Targets
I can explain when a while loop should be used.
I can identify sequence, selection, and iteration in a Python program.
I can explain how these three structures work together to create complete programs.
Unit Reflection
Look How Far We've Come!
Python Toolbox 1.0
Information
- • variables
- • strings
- • integers
- • floats
- • lists
I / O
Talk with users
Decisions
- • if
- • elif / else
- • ==, !=, <, >
- • and
Repeating
- • for loop
- • range()
- • score += 1
Code Craft
- • indentation
- • # comments
- • testing
- • debugging
Today we add one final tool to complete our toolkit:
while
WARM-UP
What Does This Code Do?
warmup.py Python 3
for i in range(5):
print("Hello")
1 How many times will this repeat?
Think about the exact count and values of i.
2 How does Python know when to stop?
What role does range(5) play in setting the boundary?
3 When would a for loop be useful?
What kind of tasks require counting a set number of repetitions?
Turn & talk with your partner for 60 seconds before sharing. Do not shout answers!
The New Challenge
What If We Don't Know How Many Times?
Real situations where counting fails:
Keep asking until the user enters a valid answer
Keep playing a game until someone wins 3 rounds
Keep collecting data until the user says "done"
Keep trying until a condition becomes false
New Python Keyword
while
Definition
A while loop repeats code as long as a condition remains true.
When the condition turns False, Python immediately stops repeating and moves on!
Syntax Anatomy
Basic while Loop Structure
4 Core Parts
counter_loop.py ● Live Code
count = 0
while count < 5:
print(count)
count += 1
1
Starting Value:
count = 0 sets up the loop's starting point.
2
Condition:
count < 5 tested BEFORE each repeat.
3
Indented Repeated Code:
Runs only when the condition evaluates to True.
4
Update / Step:
count += 1 brings the loop closer to stopping.
Python Rule: Python checks the condition before every single repetition. If True, run body. If False, exit!
Step-by-Step Execution
Trace the Loop: What Happens Line by Line?
Target: while count < 3
Check #1 TRUE
0 < 3 → True
Action:
Prints: 0
Update:
count becomes 1
↻ Loops back up
Check #2 TRUE
1 < 3 → True
Action:
Prints: 1
Update:
count becomes 2
↻ Loops back up
Check #3 TRUE
2 < 3 → True
Action:
Prints: 2
Update:
count becomes 3
↻ Loops back up
Final Check FALSE
3 < 3 → False
Action:
Does NOT print
Result:
Loop exits immediately!
⏹ STOP
Key Takeaway: The loop stops the instant its condition becomes False.
BEWARE
The Infinite Loop Problem
Dangerous Code!
infinite_bug.py
count = 0
while count < 5:
print(count)
# Notice anything missing here?
What is wrong with this program?
count is never updated! It stays 0 forever. The condition 0 < 5 remains True forever!
Term to Know
Infinite Loop
A loop that never reaches a stopping condition and repeats indefinitely until forced to stop.
Golden Rule: Inside a while loop, something MUST change to eventually make the condition False!
Core Comparison
When Do We Use Which?
Choosing the Right Loop
for loop Count-Controlled
Use when you already know how many times something should repeat.
for i in range(5):
Plain English Meaning:
"Repeat this code exactly 5 times."
for = Known Repetition
while loop Condition-Controlled
Use when repetition depends on a condition or event.
while score < 3:
Plain English Meaning:
"Keep repeating until score reaches 3."
while = Condition-Controlled Repetition
Known beforehand? Use for Unknown / event-driven? Use while
Game Programming Connection
Connecting Back to Rock, Paper, Scissors
Last Week: Fixed Rounds for loop
for i in range(5):
Forces the game to play exactly 5 rounds, even if one player has already won 3–0 or both players keep tying!
Today: True Match Play while loop
while player < 3 and cpu < 3:
Meaning: "Keep playing as long as BOTH scores are below 3." As soon as either player hits 3 wins, the condition becomes False and the match ends!
Best-of-Five Match: Just like real tournament playoffs! Games could take 3 rounds, 4 rounds, or 5 rounds—a while loop naturally handles this uncertainty.
PREDICTION CHALLENGE
Predict the Outcome
predict_loop.py Trace carefully
player_score = 2
computer_score = 1
while player_score < 3 and computer_score < 3:
print("Play another round")
player_score += 1
1 Will the loop run at all?
Check: Is 2 < 3 and 1 < 3 True or False at the start?
2 How many times will it print?
How many rounds pass before a score reaches 3?
3 Why does it stop?
Which part of the and condition becomes False?
Silent think time: 30 seconds Hold your fingers up (1, 2, or 3) when prompted!
Real-World Computing
while Loops Beyond Games
Data Science Preview
collect_responses.py Data Collector
answer = ""
while answer != "done":
answer = input(
"Enter response or type done: "
)
Unknown Amount of Data
The program has no way of knowing beforehand whether 3 people, 30 people, or 300 people will enter responses.
Sentinel Value ("done")
It keeps collecting responses continuously until the special stopping word "done" is entered.
Unit Connection: This is one major way programming connects directly to our next unit: Data Science!
Big Picture Synthesis
The Three Fundamental Programming Structures
Every program you have written—and every question on your quiz—builds on these three pillars.
Sequence
Instructions happen in a specific, predictable order.
Top → Bottom
Selection
The program makes a decision based on a condition.
if / elif / else
Iteration
The program repeats instructions multiple times.
for & while
Quiz Alert: You will need to define, identify, and explain all three on your upcoming assessment!
Structure 1 of 3
Sequence
Order Matters
Definition
Sequence means instructions happen in a specific, top-to-bottom order.
Ponder This:
What would happen if line 2 tried to run before line 1?
Python would crash with a NameError because name wouldn't exist yet!
sequence_flow.py Line by Line
1 ↓
name = input("What is your name? ")
2 ↓
print("Hello,", name)
3 ↓
score = 0
Core Principle: Python generally executes code strictly from top to bottom unless selection or iteration changes the flow.
Structure 2 of 3
Selection
Making Decisions
Definition
Selection means the program chooses which instructions to execute based on a condition.
Condition:
A question evaluated as True or False (score > 5)
Possible Paths:
Branch A vs. Branch B (only one path runs!)
selection_branch.py Decision Tree
if score > 5:
print("You win!")
else:
print("Keep trying!")
Keywords in Python:
if elif else
Structure 3 of 3
Iteration
Repeating Actions
Definition
Iteration means repeating instructions multiple times.
for loop Known Repetitions
for i in range(5):
print("Hello")
Controlled by a counted sequence or range.
while loop Condition-Controlled
while score < 3:
print("Play again")
Controlled by whether a condition remains True.
Both for and while are forms of ITERATION. They just control the loop differently!
SPOT THE STRUCTURE
Find the Three Structures
find_structures.py Look closely at every line
1player_score = 0
2while player_score < 3:
3player = input("Choose rock, paper, or scissors: ")
4if player == "rock":
5print("You chose rock.")
6player_score += 1
7print("Game over")
Where is Sequence?
Which lines run strictly one after another?
Where is Selection?
Which lines make a decision based on input?
Where is Iteration?
Which lines cause repetition?
Examine the code with your partner. Let's reveal the labeled breakdown! →
Answer Key
The Three Structures Revealed!
All 3 Working Together
Line 1: player_score = 0
Line 2: while player_score < 3:
L3: player = input(...)
L4: if player == "rock":
L5: print("You chose rock.")
L6: player_score += 1
Line 7: print("Game over")
1. Sequence
Lines 1 runs first, then loop executes, and line 7 runs after loop completes.
2. Iteration
Line 2 controls repeating lines 3–6 until player_score >= 3.
3. Selection
Lines 4–5 check user choice and decide whether or not to print the message.
Every complete program is built like a sandwich: sequence outside, loops repeating, and conditionals deciding!
System Architecture
How They Work Together
Real programs combine all three structures into a unified flow.
1
SEQUENCE
Set up starting variables, scores, and welcome messages
2
ITERATION
Repeat game rounds or data collection cycles
3
SELECTION
Decide what happens inside each round based on conditions
4
SEQUENCE
Update scores, print round results, and check exit conditions
A program rarely uses just one structure—they are designed to be composed together.
Synthesis in Action
Connect Back to Rock, Paper, Scissors
RPS Architecture
player_score = 0
computer_score = 0
while player_score < 3 and computer_score < 3:
# get player & computer choices
if player == computer:
# tie
elif player_wins:
player_score += 1
else:
computer_score += 1
print("Match over! Announce winner.")
Can you spot all three?
Sequence:
Setting initial scores to 0 at top; announcing winner at very end.
Iteration:
The while loop keeping the match alive until someone reaches 3 wins.
Selection:
The if / elif / else logic evaluating who won the current round.
Notice how naturally clean the program becomes when using the right structure for each job!
CHECK FOR UNDERSTANDING
Quick Concept Check
Q1. Which structure is used when instructions happen in a particular order? Think: Top to bottom
Q2. Which structure is represented by if, elif, and else? Think: Decision making
Q3. Which structure is represented by both for and while loops? Think: Repetition
Q4. When would you choose a while loop instead of a for loop? Think: Count vs. condition
Q5. What causes an infinite loop to occur? Think: Missing update
Be ready for cold-call answers! Answers will NOT be revealed on screen—practice out loud!
Quiz Prep Simulation
Read the Code
Code Tracing Assessment
trace_quiz.py Read line-by-line
1number = 1
2while number < 4:
3if number == 2:
4print("Two!")
5else:
6print(number)
7number += 1
1. What will this program print?
Trace line by line for number = 1, 2, 3.
2. Where is the selection?
Identify the exact line numbers.
3. Where is the iteration?
Which line controls repetition?
4. What line prevents an infinite loop?
What updates the counter?
5. What is happening in sequence?
How do initialization and updates flow?
This mirrors the exact style of code-reading questions on your programming unit quiz!
Complete Reference
Final Python Toolbox
Ready for Assessment
Store Info
variables
lists [ ]
Input / Output
input()
print()
Selection
if / elif / else
Iteration
for
while
Compare
== , !=
< , > , <= , >=
Logic
and
Booleans
Update
+= 1
counter
Practices
# comments
indentation
🎉 You now have the foundational tools needed to read, understand, and modify simple Python programs!
Looking Forward
Python Isn't Going Away
Next: Data Science
How programming powers Data Science:
Collect data from users and automated sensors
Organize and clean raw survey entries
Calculate summaries (averages, totals, maximums)
Interpret results and draw real conclusions
Your Skills in Action
while loops → Collect entries until user types done
lists [ ] → Store large datasets and sample rows
counters → Tally survey frequencies and counts
conditionals → Filter and categorize records
Python was not a separate detour—it is our primary superpower for working with data!
Individual Assessment
Exit Ticket
10 Minutes • Submit Before Leaving
1. While Loops
In your own words, what does a while loop do?
2. Loop Contrast
What is the difference between a for loop and a while loop?
3. Define Sequence
What does sequence mean in programming?
4. Define Selection
What does selection mean in programming?
5. Define Iteration
What does iteration mean in programming?
6. Python Examples
Identify one Python example of each structure (Sequence, Selection, Iteration).
7. Data Science Connection
Why might programming be useful in our upcoming Data Science unit?
Write answers on your paper or digital exit slip. Great work throughout this Python unit!