Programming · Grade 7 · Chapter 7
Python Loops
Automating repetitive tasks using `for` loops, `while` loops, and `range()`.
Chapter Goals
What We Will Master Today
- DRY Principle: Replace repeated copy-pasted code with clean loops.
- For Loops & range(): Master count-controlled iteration with start, stop, and step.
- While Loops: Implement condition-controlled iteration.
- Loop Control: Use `break` to exit early and `continue` to skip iterations.
Core Principle
D.R.Y: Don't Repeat Yourself!
Imagine writing 1,000 lines of print("Hello") to show 1,000 greetings. What if you wanted to change "Hello" to "Welcome"? You'd have to edit 1,000 lines!
Solution: Loops run a single block of code as many times as you tell Python to!
Language Comparison
Scratch Repetition vs Python for Loops
Scratch Visual Block
repeat (5)
say "Hello!" for 1 secs
Python Text Syntax
for i in range(5):
print("Hello!")
Core Concept 1
Anatomy of a for Loop
for item in range(3):
print("Iteration number:", item)
item is the loop variable that holds the current count.
range(3) generates numbers: 0, 1, 2 (Starts at 0!).
- The loop body executes 3 times total.
Core Concept 2
The 3 Flavors of range()
range(stop)
range(5)
Generates: 0, 1, 2, 3, 4
range(start, stop)
range(1, 6)
Generates: 1, 2, 3, 4, 5
range(start, stop, step)
range(0, 10, 2)
Generates: 0, 2, 4, 6, 8
Off-By-One Trap
range(1, 5) Excludes the Stop Number!
In Python's range(start, stop), the loop stops BEFORE reaching the stop number.
range(1, 5) will loop for 1, 2, 3, 4 — it will NOT include 5!
Loop Tracing
Tracing a for Loop Line-by-Line
total = 0
for num in range(1, 4):
total = total + num
print("Final sum:", total)
Core Concept 3
The Condition-Driven while Loop
A while loop keeps repeating as long as its Boolean condition stays True.
count = 3
while count > 0:
print("Countdown:", count)
count = count - 1 # Decrement counter!
print("Blastoff! 🚀")
Visual Flow
while Loop Execution Diagram
TRUE
Execute Loop Body & Update Counter
FALSE
Exit Loop & Continue Script
Danger Zone
The Dreaded Infinite Loop ♾️
# Broken Code - Forgot to update counter!
i = 1
while i < 5:
print("Stuck in a loop!")
# Missing: i = i + 1
Warning: If your terminal freezes, press Ctrl + C to force kill the running script!
Smartboard Voting
How Many Times Will This Loop Print "Python"?
x = 10
while x > 4:
print("Python")
x = x - 2
A) 3 times (for x = 10, 8, 6)
Core Concept 4
Breaking Out Early with break
The break keyword immediately stops the loop, jumping straight to lines after the loop.
for num in range(1, 10):
if num == 4:
break # Exit loop completely!
print(num)
# Console Prints: 1, 2, 3
Core Concept 5
Skipping Iterations with continue
The continue keyword skips the remaining code in the current iteration and jumps to the next one.
for num in range(1, 6):
if num == 3:
continue # Skip printing 3!
print(num)
# Console Prints: 1, 2, 4, 5
Control Keywords
break vs continue
break
Destroys the loop completely. No remaining iterations will run.
continue
Skips rest of current turn, but continues with next loop iteration.
Decision Guide
When to Use for vs while
Use for Loop
When you know the EXACT number of iterations in advance (e.g. repeat 10 times, count items in a list).
Use while Loop
When repeating until an event happens (e.g. until user types "quit", until player lives reach 0).
Quick Check · Quiz 1
What numbers are generated by range(2, 6)?
A2, 3, 4, 5, 6
B2, 3, 4, 5
C0, 1, 2, 3, 4, 5
D2, 4, 6
Click to reveal answer
Quick Check · Quiz 2
What causes a while loop to become infinite?
AUsing a string variable
BThe condition never evaluates to False
CUsing the print function
DSetting count equal to 0
Click to reveal answer
Quick Check · Quiz 3
What keyword immediately skips the rest of the current iteration and jumps to the next loop cycle?
Abreak
Bcontinue
Cpass
Dstop
Click to reveal answer
Quick Check · Quiz 4
What will range(0, 10, 3) produce?
A0, 3, 6, 9
B0, 3, 6, 9, 12
C3, 6, 9
D0, 1, 2, 3
Click to reveal answer
Guided Practice
Build a PIN Retry Security System
correct_pin = "4321"
attempts = 0
while attempts < 3:
entered = input("Enter 4-digit PIN: ")
if entered == correct_pin:
print("Access Granted! 🔓")
break
attempts = attempts + 1
print("Wrong PIN. Attempts left:", 3 - attempts)
Coding Pattern
The Accumulator Pattern (Summing Values)
total_score = 0
for round_points in [10, 25, 15, 50]:
total_score = total_score + round_points
print("Total points earned:", total_score) # Outputs 100
Common Trap
Misconception: Loop Variables Reset Automatically
Variables modified inside a loop retain their updated values after the loop finishes!
Summary & Takeaways
What We Learned in Chapter 7
- Loops automate repetitive tasks adhering to the DRY principle.
for i in range(start, stop, step) runs a set number of times.
while condition: repeats as long as its condition remains True.
- Use
break to abort a loop and continue to skip one turn.
Cheat Sheet
Loop Syntax Quick Reference
# Counted For Loop:
for i in range(1, 11):
print(i)
# Conditional While Loop:
while energy > 0:
energy -= 1
Exit Ticket
Trace the Output
What will this script print?
for n in range(5, 0, -1):
print(n)
Next Chapter: Python Functions (def & return)!