Lesson 8 of 30
In progress
Repeat work with for loops and range
Loop over numbers and text, accumulate totals, and stop copying the same line five times with a clear for loop.
Copy-paste is not repetition. If you write the same line five times, the sixth time you need it will be the time you make a mistake. A for loop says the thing once and tells Python how many times to do it.
What you will learn
- Loop over a range of numbers and over the characters in text.
- Accumulate a total and count matching items.
- Choose sensible start and stop values with
range().
A loop is a conveyor belt
Think of a factory belt carrying boxes past a worker. The worker does the same job on each box and does not care how many boxes there are. A for loop takes each item from a collection, one at a time, and runs the body with that item.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
Press Run to see the output.
range(1, 6) produces 1, 2, 3, 4, 5. The stop value is never included. That single rule explains most off-by-one confusion: if you want to reach 5, stop at 6.
range(5) is shorthand for range(0, 5) and produces five values starting at zero. range(0, 10, 2) adds a step and produces 0, 2, 4, 6, 8. The step can be negative: range(5, 0, -1) counts down to 1, which is what you want for a countdown.
Loop over things, not just numbers
The loop variable can take each character of a string, each item of a list, or each key of a dictionary.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for letter in word:
print(letter.upper())
Press Run to see the output.
This is often clearer than indexing with range(len(word)). Reach for the item directly unless you genuinely need the position as well.
Accumulate a result
A loop usually builds something: a total, a count, or a new list. Start with an empty value before the loop and update it inside.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for price in prices:
total = total + price
print("Total:", total)
passing = 0
scores = [45, 72, 88, 51]
for score in scores:
if score >= 50:
passing = passing + 1
print("Passing scores:", passing)
Press Run to see the output.
total = total + price is the pattern to memorise, and total += price is the shorthand. Beginners often print inside the loop when they wanted the total once at the end. Printing inside is right when the reader needs a running log; printing after is right when they need one answer.
Loop with an index when you need one
Sometimes the position matters as well as the item. for index in range(len(items)): gives both, but enumerate is cleaner: for index, item in enumerate(items):. The index starts at zero; pass start=1 when you are numbering for a person rather than for Python.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for number, step in enumerate(steps, start=1):
print(number, step)
Press Run to see the output.
Use the position for output, not for reaching back into the list. If you find yourself writing items[index] inside the loop, you probably wanted the item that enumerate already gave you.
Nested loops
A loop inside a loop runs the inner loop completely for every pass of the outer loop.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
Press Run to see the output.
The end=" " keeps output on one line, and the empty print() starts a new line after each row. Nested loops are how you build tables and grids, and how you accidentally make a program slow if both loops are large. Two loops over a thousand items is a million passes, which is fine once and painful inside another loop.
Changing the list you are looping over is a common source of skipped items. If you remove items from a list inside the for loop that is iterating it, the next item shifts into the position you just left. Build a new list instead, or loop over a copy.
Print the multiplication table for 7, from 7 x 1 to 7 x 10, one line per result. Then add a second loop that sums all ten results and prints the total.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for number in range(1, 11):
product = 7 * number
total += product
print(f"7 x {number} = {product}")
print("Sum of the table:", total)
Press Run to see the output.
range(1, 11) gives 1 through 10. The total is accumulated in the same loop, which is more efficient than looping twice.
Recap
fortakes each item from a sequence and runs the body with it.range(start, stop)excludesstop;range(stop)starts at zero.- Accumulate outside the loop and print once when you want a total.
Next, you will use while loops for the cases where you do not know in advance how many repetitions are needed.
Why does range(1, 5) not include 5?
Can I loop backwards?
”Does
Progress is saved in this browser only. No account, no email.