2. Making Decisions & Looping
Repeating Work with for Loops & range()
Stop copying and pasting repetitive code: understand how for loops walk through items one by one, count with range(), add totals step by step, and track item numbers.
- Repeat actions over lists and sequences with for loops
- Generate numeric sequences with range(start, stop)
- Calculate running totals and number items cleanly with enumerate()
Imagine you run an online shop and need to send a "Thank you for your order!" message to 1,000 customers. You definitely cannot type print(...) 1,000 times!
Whenever you need the computer to repeat the same action on every item in a list—or repeat an action a fixed number of times—you use a for loop.
How a for Loop Works
A for loop pulls one item at a time from your list until every item has been visited.
Imagine you have a stack of 3 envelopes (["Alex", "Maya", "Sam"]). You pick up the first envelope, write a greeting, set it down, and pick up the next one until the stack is empty.
In Python, that looks like this:
names = ["Alex", "Maya", "Sam"]
for name in names:
print(f"Hello, {name}!")
print("All done!")Let's watch what Python does turn by turn:
- Turn 1:
namebecomes"Alex"→ printsHello, Alex! - Turn 2:
namebecomes"Maya"→ printsHello, Maya! - Turn 3:
namebecomes"Sam"→ printsHello, Sam! - No more names left → loop ends, and the unindented line prints
All done!once.
Notice name is just a temporary variable name you pick. You could write for friend in friends: or for price in prices:—pick whatever makes the line read like English!
Repeating a Number of Times with range()
What if you don't have a list of names—you just want to count from 1 to 5? Use Python's built-in range() helper:
range(5)gives0, 1, 2, 3, 4(5 numbers starting from 0, stopping BEFORE 5)range(1, 6)gives1, 2, 3, 4, 5(starts at 1, stops BEFORE 6)
for num in range(1, 6):
print(f"Count: {num}")Why does range(1, 6) stop at 5? In Python, ranges always include the start number (1) and stop just before the end number (6). So range(1, 11) gives 1 through 10!
Adding Up a Total Step by Step
One of the most useful things a for loop can do is add up numbers (like items in a shopping cart):
prices = [12, 8, 25]
total = 0
for price in prices:
total = total + price
print(f"Total: ${total}")Let's watch total change on every turn of the loop:
| Turn | Current price | Math Done (total + price) | New total |
|---|---|---|---|
| Before loop starts | — | — | 0 |
| Turn 1 | 12 | 0 + 12 | 12 |
| Turn 2 | 8 | 12 + 8 | 20 |
| Turn 3 | 25 | 20 + 25 | 45 |
Why did we write total = 0 BEFORE the loop?
If you accidentally put total = 0 inside the loop, it would reset your total back to zero on every single turn!
Numbering Items While Looping (enumerate)
Sometimes you want to print "1. Milk", "2. Eggs", "3. Bread". Instead of creating a manual counter variable, Python gives you enumerate(list, start=1) which hands you both the number and the item on every turn:
groceries = ["Milk", "Eggs", "Bread"]
for number, item in enumerate(groceries, start=1):
print(f"{number}. {item}")Common Beginner Mistakes
- Putting
print(total)inside the loop by accident: Ifprint(total)is indented inside theforblock, it prints the running total after every item instead of once at the end. Unindent it when you only want the final answer! - Off-by-one with
range(): Rememberrange(1, 5)prints1, 2, 3, 4(it stops before5).
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Write a for loop using range(1, 11) that adds up only the even numbers from 1 to 10 (2 + 4 + 6 + 8 + 10) and prints the result (30).
Quick Checkpoints
What numbers does range(1, 5) produce?
Why should total = 0 be placed BEFORE a for loop instead of inside it?