The order for table 3: coffee with milk, sweet tea, toast. To print "Making ..." for each item, you could write print three times. But tomorrow the order has 12 items, and the day after it has 40. You never know the number in advance. Writing print once for every item is clearly not practical.
A for loop solves that problem. It repeats one block of code for each item of a sequence (a set of values in order), from the first to the last, and then stops by itself. A for loop works the way Mr. Darto reads the order slip. The first line says "coffee with milk", so he makes a coffee with milk. The second line says "sweet tea", so he makes a sweet tea. He continues until the last line. In this picture, the order slip is the sequence, and making the item is the block of code that repeats. Mr. Darto's finger, which points at the line he is working on, is the loop variable: the name stuck onto the item being worked on.
Repeat for each item of a list
A list is a row of values between square brackets, separated by commas. The List lesson explains it in full. For now, you only need to know that for can read its items one at a time:
order = ["coffee with milk", "sweet tea", "toast"]
for item in order:
print("Making", item)
print("The whole order is ready")
The result:
Making coffee with milk
Making sweet tea
Making toast
The whole order is ready
for item in order:means "for each item oforder, stick the nameitemonto that item, then run the block". The colon at the end of the line is required.- The lines indented by 4 spaces below it are the loop body. The loop body runs once for each item. One run is called one pass (an iteration).
print("The whole order is ready")is not indented, so it is not part of the loop. It runs once, after all the passes are finished.itemis the loop variable. You can choose its name freely. Choose a name that says what it holds.
A string is a sequence too: for letter in "milk": runs its body 4 times, with letter holding m, i, l, then k.
Adding up with a loop
The most common pattern at the till: prepare a running total (a variable that holds the sum so far), then add one item to it on every pass.
prices = [15, 5, 12]
total = 0
for price in prices:
total += price
print("Total:", total) # Total: 32
In this code the running total is total, and price is the price being read. Here is total on each pass:
| Pass | price |
total before |
total after |
|---|---|---|---|
| 1 | 15 | 0 | 15 |
| 2 | 5 | 15 | 20 |
| 3 | 12 | 20 | 32 |
total += price is short for total = total + price: Python adds price to the value of total, then stores the result in total again. total = 0 is written before the loop. If you put it inside the loop, the running total goes back to 0 on every pass.
range(): a sequence of numbers
Do you need numbers in order, for example queue numbers? Use range(). The pattern is range(start, stop, step): begin at start, go up by step each time, and stop before stop. The number stop itself is never included, the same as the stop index of slicing in the Strings in Python lesson.
| Call | Numbers it gives | How many |
|---|---|---|
range(5) |
0, 1, 2, 3, 4 | 5 |
range(1, 6) |
1, 2, 3, 4, 5 | 5 |
range(0, 10, 2) |
0, 2, 4, 6, 8 | 5 |
range(10, 0, -3) |
10, 7, 4, 1 | 4 |
range(5, 1) |
(empty) | 0 |
- If there is only one number, it is
stop, andstartis 0. Sorange(5)gives 0 to 4: five numbers, without 5. Ifstepis not written, the numbers go up by 1. - A negative
stepcounts down, andstopis still not included. range(5, 1)is empty. When counting up, 5 is already past 1, so the loop body does not run even once. There is no error.- Want 1 to
n? Writerange(1, n + 1).
For example, for i in range(1, 5): print(i) prints four lines, 1 to 4. The number 5 is not included. (A loop body of only one line may be written right after the colon.)
enumerate(): the number and the item
A receipt needs a line number in front of each order. enumerate() gives a number and an item together on every pass:
order = ["coffee with milk", "sweet tea", "toast"]
for num, item in enumerate(order, start=1):
print(f"{num}. {item}")
The result:
1. coffee with milk
2. sweet tea
3. toast
- On each pass,
enumerategives two values.num, itemtakes both at once: the first value (the number) goes intonum, the second (the item) intoitem. - Without
start=1the numbers begin at 0, like an index:for i, v in enumerate(["a", "b", "c"]): print(i, v)prints three lines,0 a,1 b,2 c. - The number of passes always equals the number of items in the list.
Loops and if: FizzBuzz
The loop body may hold if, elif and else. One example is the classic FizzBuzz puzzle, which you solve in this lesson's exercise. For each number from 1 to n, print one line, with these rules:
- a multiple of both 3 and 5 becomes
FizzBuzz, - a multiple of 3 only becomes
Fizz, - a multiple of 5 only becomes
Buzz, - any other number is printed as it is.
"A multiple of 3" means the remainder is 0 when you divide by 3. If i is the number the loop is reading, a multiple of 3 is checked with i % 3 == 0. Some examples for values of i:
i |
i % 3 |
i % 5 |
Printed |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 3 | 0 | 3 | Fizz |
| 5 | 2 | 0 | Buzz |
| 9 | 0 | 4 | Fizz |
| 15 | 0 | 0 | FizzBuzz |
The order of the checks decides the result. 15 passes the multiple-of-3 check and the multiple-of-5 check. If i % 3 == 0 is checked first, the elif lines after it are never read, and 15 becomes only Fizz. So check for a multiple of both 3 and 5 first. The condition is i % 15 == 0, because a multiple of both 3 and 5 is always a multiple of 15. You can also write i % 3 == 0 and i % 5 == 0.
⚠️ Colons, indentation and the last number left out
- Forgetting the colon.
for item in orderwithout:is refused withSyntaxError: expected ':', and Python points at thatforline. - A loop body that is not indented. A
print(item)line that starts at the left edge givesIndentationError: expected an indented block after 'for' statement on line 2. - Thinking
stopis included.range(1, 5)stops at 4. To reach 5, writerange(1, 6), orrange(1, n + 1)for 1 ton. - Looping directly over a number.
for i in 5:fails withTypeError: 'int' object is not iterable(an int can't be read one item at a time). A number is not a sequence, so userange(5)instead.
TL;DR: for item in sequence: runs the loop body (the indented lines) once for each item of the sequence, then stops by itself. The sequence can be a list, a string or a range(). range(start, stop, step) gives numbers in order and stops before stop: range(5) is 0 to 4, range(1, 6) is 1 to 5, and range(0, 10, 2) is 0, 2, 4, 6, 8. A negative step counts down. enumerate(list, start=1) gives the number and the item together: for num, item in .... To add things up, set total = 0 before the loop and write total += price inside it. In FizzBuzz, check for multiples of 15 first, then 3, then 5.
⚡ Once for each item
Write:
order = ["coffee with milk", "sweet tea", "toast"]
for item in order:
print("Making", item)
print("The whole order is ready")
Meaning: order is a list (a row of values between square brackets). for item in order: sticks the name item onto each item of order, one at a time, then runs the indented lines below it. One run is called one pass. A line that isn't indented isn't part of the loop: it runs once, after all the passes are finished.
⚡ Adding up with a loop
Write:
prices = [15, 5, 12]
total = 0
for price in prices:
total += price
print("Total:", total) # Total: 32
Meaning: total += price is short for total = total + price: on every pass, price is added to total. total = 0 goes before the loop. If you put it inside the loop, total goes back to 0 on every pass.
⚡ range() stops before stop
Guess first: how many lines does for i in range(1, 5): print(i) print?
Four: 1, 2, 3, 4. The number 5 is not included.
Meaning: range(start, stop, step) gives numbers in order from start, and stops before stop. range(5) is 0 to 4. Want 1 to n? Write range(1, n + 1).
⚡ The number and the item
Write:
order = ["coffee with milk", "sweet tea", "toast"]
for num, item in enumerate(order, start=1):
print(f"{num}. {item}")
Guess first: without start=1, what's the first number?
0, like an index. The number of passes is still the same as the number of items in the list.
Meaning: On each pass, enumerate gives two values: the number goes into num, the item into item.