A Python for loop takes the items of a sequence one at a time and runs the same block of code once for each item. You can loop over a list, the characters in a string, or a range of numbers made by range().
In this post you will use a for loop at Corner Café, a small café in the fictional port city Port Alder. You will count with range, loop through a list, get an index, and stop a loop early.
Why do you need a for loop?
Ada owns Corner Café, and it has 5 tables. Every morning she wants to print a "ready" message for each table:
print("Table 1 is ready") print("Table 2 is ready") print("Table 3 is ready") print("Table 4 is ready") print("Table 5 is ready")
This works. With 50 tables you would need 50 lines, and every change means editing every line. A loop lets the computer repeat the work for you.
How does a for loop work in Python?
A for loop assigns the next value to a variable, runs the indented block, and repeats until the values run out:
for table in range(1, 6): print(f"Table {table} is ready")
Read it line by line:
for table in ...:puts the next value into the variabletableon each turn.range(1, 6)makes the numbers 1, 2, 3, 4, 5. It starts at 1 and stops before 6.- The indented lines after the colon are the loop body. They run once per turn.
Indentation is required in Python. All lines in the body must be indented by the same amount, usually 4 spaces.
How does range work in a for loop?
range makes a sequence of integers. You can give it one, two, or three numbers:
| Code | Numbers it makes | Use it to |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | Repeat something 5 times |
range(1, 6) | 1, 2, 3, 4, 5 | Count in a fixed range |
range(0, 20, 5) | 0, 5, 10, 15 | Count in steps |
The end value is never included. range(1, 5) does not contain 5. To count from 1 to 5, write range(1, 6).
To count down, use a negative step:
for seconds in range(3, 0, -1): print(seconds) print("Corner Café is open!")
The loop stops when it reaches 0 and does not produce 0. The last line has no indentation, so it is outside the loop and runs only once.
How do you loop through a list in Python?
Put the list after in. Python gives you each item directly:
menu = ["tea", "latte", "cookie"] for item in menu: print(item.upper())
The loop prints TEA, LATTE, and COOKIE. You choose the name of the loop variable. x would work, but a clear name like item makes the code easier to read.
You can also loop over a string, one character at a time:
order = "latte" letter_count = 0 for letter in order: letter_count += 1 print(letter_count)
This prints 5. In real code you would use len(order), but this example shows how a loop walks through text.
How do you use a for loop with an index?
Use enumerate when you need the position of each item as well as the item:
menu = ["tea", "latte", "cookie"] for position, item in enumerate(menu, start=1): print(f"{position}. {item}")
The loop prints 1. tea, 2. latte, and 3. cookie. enumerate gives two values on each turn: the number and the item. Without start=1, the count begins at 0.
You will often see range(len(menu)) for this job. It works, but when you only need the items, for item in menu is shorter and easier to read.
How do break and continue work in a for loop?
break ends the loop at once. continue skips the rest of the current turn and moves to the next item.
prices = [1.25, 4.25, 0.0, 2.00, 3.75] total = 0 for price in prices: if price == 0.0: continue if total + price > 8: print("Budget reached") break total += price print(f"Total: ${total:.2f}")
Here is what happens. The price 0.0 is skipped by continue. After 1.25 and 4.25 the total is 5.50. Adding 2.00 gives 7.50, which is under the limit, so it is added. Adding 3.75 would pass 8, so the loop prints a message and stops with break.
How do you add up values with a for loop?
Adding values one by one is one of the most common loop jobs:
prices = [4.25, 1.25, 2.00, 3.75] total = 0 for price in prices: total += price print(f"Bill: ${total:.2f}")
The variable total starts at 0 before the loop, and each turn adds one price. If you set total = 0 inside the loop, it resets on every turn and you get the wrong answer.
What mistakes do beginners make with for loops?
- Missing indentation: if the body line has no indentation, Python raises an
IndentationError. - Missing colon: the
forline must end with:. - Counting the end value:
range(1, 10)does not produce 10. - Starting the total inside the loop: write
total = 0before the loop. - Using `range(len(menu))` when you only need items:
for item in menuis clearer.
What to read next
The best way to learn loops is to run them yourself. In the [for and range lesson](/learn/python/for-range) you run these examples in your browser, solve exercises, and take a 10-question test. When you do not know in advance how many turns you need, the [while, break, and continue lesson](/learn/python/while-break-continue) is the next step.
- [Python if, elif, else](/blog/python-if-elif-else)
- [Python list methods](/blog/python-list-methods)
- [Python course](/courses/python)
- #python
- #loops
- #for loop
- #range