Module 02 · Lesson 04
Definite Iteration & for Loops
Repeat work for every item with for loops: walk through strings and lists, count with range(), build running totals, and get positions with enumerate().
- About 8 minutes
- Beginner friendly
- 12-question quiz at the end
What you will learn
- Loop over items
- Count with range()
- Draw with loops
- Watch a loop go round
Repeat for every item
A `for` loop runs the same lines once for each item, so you write them only once.
for item in things
for fruit in basket:takes each item in turn and gives it the namefruit.range()
range(5)counts 0, 1, 2, 3, 4. It stops just before the number you give it.The block
The indented lines under the colon run once per item. The first line that is not indented runs after the loop.
Anything in a row
Loop over a list, the letters of a word or a
range()of numbers.
Loops run the world
Whenever a computer does the same thing many times, a loop is doing the work.
- PlaylistsFor every song in the playlist: play it, then move to the next one.
- GamesFor every enemy on screen: move it one step, sixty times a second.
- Photo appsFor every photo in an album: make a small preview picture.
- Class registersFor every name on the list: call it out and tick who is here.
The first line of a loop
Every `for` loop starts with a line like this. Tap each part to see its job.
Part 1 of 7
keyword:for starts a loop that will visit items one at a time.
Loops draw shapes
A turtle pen walks forward and turns. Put those two moves in a `for` loop and they repeat. Pick a shape or slide the numbers, and watch the loop under the drawing change.
Shape 1 of 5Square
Real Python opens the turtle in its own window, so here the drawing is a preview of what the code does.
Change the numbers
import turtle t = turtle.Turtle() for i in range(4): t.forward(120) t.right(90)
Challenges0 of 3
- Make a triangle: 3 sides, and turns that add up to 360 degrees.
- Make a ten-point star: 10 lines that turn 108 degrees each time.
- Make a flower with 10 circles that fill the whole turn.
Loop over things
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Every item
The loop gives each item in the list the name fruit, one at a time.
Your turn: Add two more fruits to the list. How many times does All done print?
for fruit in ["apple", "pear", "plum"]:
print("I like", fruit)
print("All done")Press Run to see what it prints.Watch a loop go round
Press Step to run one line at a time. Watch Python jump back up to the `for` line.
Ready. Press Step to run the first line.
- total = 0
- for coins in [3, 5, 2]:
- total += coins
- print("Total:", total)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Counting to three, three ways
The same loop, printing 0, 1 and 2, in Python and two other languages.
Language 1 of 2Python vs JavaScript
for n in range(3):
print(n)Two lines. range(3) does the counting, and indentation marks the block.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.How many times does hi appear?
for n in range(3):
print("hi")0 of 6 answered
Common loop misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
for item in collection: # list, string, range ...
...
range(5) range(1, 6) range(10, 0, -2) # stop is never included
for i, item in enumerate(items, start=1):
for a, b in zip(list_a, list_b):
total = 0 # accumulator: set before,
for x in values: # update inside,
total += x
print(total) # use afterPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A shopping receipt
Print each item of a basket with its number, and the total at the end, using enumerate() and an accumulator.
items = ["bread", "milk", "eggs"]
prices = [1.2, 0.95, 2.1]
total = 0
for number, (item, price) in enumerate(zip(items, prices), start=1):
print(f"{number}. {item:<6} {price:.2f}")
total += price
print(f"Total: {total:.2f}")Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Expecting range to include the stop
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
for day in range(1, 7):
print("Day", day)Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Health and fitness
Weekly step summary
A walking app looks at a week of step counts and reports the total, the best day and how many days met the goal.
Why Python fits
One pass through the week updates three results at once: an accumulator for the total, a counter for goal days, and a running best. This is how many real reports are built.
Pythondays = ["Mon", "Tue", "Wed", "Thu", "Fri"] steps = [6200, 10400, 8100, 12050, 9900] GOAL = 10000 total = 0 goal_days = 0 best_day = "" best = 0 for day, count in zip(days, steps): total += count if count >= GOAL: goal_days += 1 if count > best: best = count best_day = day print(f"Total: {total:,}") print(f"Goal met on {goal_days} days") print(f"Best day: {best_day}")OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
What value does the loop variable have after the loop?
Can I loop backwards over a string?
When should I use for and when while?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.