Python for and while loops: make the computer do the boring shit
Updated · every example run on Python 3.9 to 3.15
Last lesson you pulled things off a shopping list one print at a time. Fine for four groceries. Now picture your bank statement: 300 transactions. You are not typing 300 print lines. Nobody is. That's what the computer is for.
A loop runs the same block of code again and again: once for every item, or until something changes. It's the thing computers are genuinely great at, doing something dull ten thousand times without getting bored or asking for a raise.
for: once for every item
for takes a list and runs its block once per item, with a name of your choice holding the current one:
groceries = ["milk", "eggs", "bread", "coffee"]
for item in groceries:
print("Buy", item)
print("Done. Go home.")Buy milk
Buy eggs
Buy bread
Buy coffee
Done. Go home.Same colon, same indent as if. Each time around, item is the next thing on the list. The name is yours: for thing in groceries does exactly the same, so pick whatever reads like English. The last line is back at the left edge, so it runs once, after the loop is done.
Adding things up as you go
The most common loop in the world: start a variable before the loop, change it on every round.
steps = [4200, 8100, 300, 12000, 6500]
total = 0
good_days = 0
for day in steps:
total += day
if day > 8000:
good_days += 1
print("Total steps:", total)
print("Days over 8000:", good_days)
print("Average:", total / len(steps))Total steps: 31100
Days over 8000: 2
Average: 6220.0total += day is short for total = total + day, and -= does the same with a minus. The counters start at zero outside the loop; put total = 0 inside it and it resets on every round, and your total is just the last day. And yes, an if inside a for is allowed. Blocks go inside blocks, one more indent each. The 300-step day, by the way, was the day you learned about if.
range: counting without a list
When you want a number of rounds rather than a list of things, use range:
for n in range(3):
print("Push-up", n)
for floor in range(1, 4):
print("Floor", floor)
for seconds in range(10, 0, -3):
print(seconds)
print(list(range(5)))
print(range(5))Push-up 0
Push-up 1
Push-up 2
Floor 1
Floor 2
Floor 3
10
7
4
1
[0, 1, 2, 3, 4]
range(0, 5)range(3) counts 0, 1, 2: it starts at zero and stops before the number you give it, like a slice. So your workout begins with push-up number zero. Very efficient. range(1, 4) starts at 1, and a third number is the step, which can go backwards.
A range isn't a list. It hands out numbers as the loop asks for them, which is why printing it just shows range(0, 5). Wrap it in list() when you want to see the numbers.
enumerate: the number and the item
Want a numbered list? enumerate gives you a count and an item on each round, and you catch both with two names:
groceries = ["milk", "eggs", "bread", "coffee"]
for number, item in enumerate(groceries, start=1):
print(f"{number}. {item}")1. milk
2. eggs
3. bread
4. coffeeWithout start=1 it counts from zero, which computers love and humans find upsetting. You'll also see people write for i in range(len(groceries)) and then groceries[i]. That works, and it's longer, uglier and the easiest place in the world to get an index wrong.
Two names, no enumerate
Forget the enumerate and keep the two names:
groceries = ["milk", "eggs", "bread"]
for number, item in groceries:
print(number, item)Traceback (most recent call last):
File "/home/me/project/main.py", line 3, in <module>
for number, item in groceries:
^^^^^^^^^^^^
ValueError: too many values to unpack (expected 2)| Python | Prints |
|---|---|
| 3.9–3.15 | ValueError: too many values to unpack (expected 2) |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
Now each item is just a string, and Python tries to split "milk" into two names, one letter each. Four letters don't go into two names, so it stops with ValueError: too many values to unpack, same words on every version from 3.9 to 3.15. The really fun part: a two-letter item would unpack without complaint, one letter per name, and print nonsense with no error at all.
while: loop until something changes
for is for when you know what you're looping over. while is for when you don't know how many rounds it will take: it checks a condition before every round and stops the first time it's false.
cat_food = 2000
per_day = 340
days = 0
while cat_food >= per_day:
cat_food -= per_day
days += 1
print("Days of food:", days)
print("Grams left:", cat_food)Days of food: 5
Grams left: 300Each round eats 340 grams and counts a day. After five days there are 300 grams left, 300 >= 340 is false, and the loop ends. Day six is going to be a damn tense morning.
Something inside a while has to change its condition. Here it's cat_food -= per_day. Forget that line and you've met the subject of the last section.
break and continue
continue skips the rest of this round and goes on to the next. break leaves the loop entirely:
transactions = [20, -5, 0, -40, 0, -100, 15]
balance = 30
for amount in transactions:
if amount == 0:
continue
balance += amount
print(amount, "->", balance)
if balance < 0:
print("Overdrawn. Stopping here.")
break
print("Final balance:", balance)20 -> 50
-5 -> 45
-40 -> 5
-100 -> -95
Overdrawn. Stopping here.
Final balance: -95The zeros never print: continue jumped over them. The -100 sinks the balance, break ends the loop, and the 15 at the end never gets added, which is the bank's favorite part. Python carries on with the first line after the loop. Both work in while loops too, and both only ever affect the loop they're directly inside.
Loops inside loops
A loop can sit inside another one. The inner loop runs all the way through on every round of the outer one:
rooms = ["A", "B", "C"]
for floor in range(1, 4):
for room in rooms:
print(f"{floor}{room}", end=" ")
print()1A 1B 1C
2A 2B 2C
3A 3B 3C Three floors times three rooms is nine room numbers. end=" " from lesson 1 keeps each floor on one line, and the empty print() finishes the line. It sits at the same depth as the inner for, so it runs once per floor. On the way back out, every line has to land on a depth some block already uses: back off to six spaces when the blocks use four and eight, and Python quits with IndentationError: unindent does not match any outer indentation level.
Nested loops multiply, so keep an eye on the sizes. 1,000 times 1,000 is a million rounds, and if each round just adds a number, Python is done in a fraction of a second. A third loop of 1,000 makes it a billion, and that takes even a fast laptop the better part of a minute, fan screaming.
The infinite loop
A while whose condition never turns false never stops. This one has nobody changing the balance:
balance = 100
while balance > 0:
print("Spending...")
It prints "Spending..." forever or until you press Ctrl+C, whichever comes first. Python then stops with a KeyboardInterrupt traceback. It looks dramatic. Nothing is broken except your plan. Everybody writes one of these eventually; the Ctrl+C is the fucking rite of passage.
Sometimes you want a loop with no end on purpose, and you leave it from the inside with break. That's while True:
balance = 100
coffees = 0
while True:
balance -= 6
coffees += 1
if balance < 6:
break
print("Coffees bought:", coffees)
print("Left:", balance)Coffees bought: 16
Left: 4True is always true, so only the break gets you out. Since the check comes at the end of the block, the body always runs at least once. Sixteen lattes later, there's $4 left.
Try it yourself
A week of temperatures: temperatures = [12, 17, 21, 25, 19, 30, 8]. With one for loop, count the days at 20 or above and find the highest temperature, without using max().
Show the answer
temperatures = [12, 17, 21, 25, 19, 30, 8]
warm_days = 0
hottest = temperatures[0]
for temp in temperatures:
if temp >= 20:
warm_days += 1
if temp > hottest:
hottest = temp
print("Warm days:", warm_days)
print("Hottest:", hottest)
Start hottest at the first item, not at 0: a winter week where every day is below zero would otherwise report 0 as the hottest. Python's max(temperatures) does the same job in one go, and now you know what it does inside.
Questions
How do I loop through a list with an index in Python?
Use enumerate: for i, item in enumerate(groceries): gives you both. for i in range(len(groceries)) works too, but it's longer, and counting indexes by hand is exactly how you end up asking for one past the end and getting an IndexError.
How do I stop an infinite loop in Python?
Press Ctrl+C in the terminal where it's running. Python stops with a KeyboardInterrupt, and you fix whatever was supposed to make the condition false.
Does Python have a do-while loop?
No. Write while True: and end the block with if <done>: break. The body then always runs at least once, which is all a do-while is.
What is the difference between a for loop and a while loop?
for runs once per item of something you already have: a list, a string, a range. while keeps going as long as a condition is true, for when you can't know in advance how many rounds it will take.
Sources
- More control flow tools: for statements, Python documentation
- The range() function, Python documentation
- break and continue statements, Python documentation
- The while statement, Python documentation
- Built-in functions: enumerate, Python documentation
- Built-in exceptions: KeyboardInterrupt, Python documentation
Read on November 11, 2026.