Choose one small job
Blink a light, draw a star, or say “beep.” Keep the repeated job tiny.
05LOOPS · FOR
A loop repeats one small job and knows when to stop.
LOOK FIRST
Blink a light, draw a star, or say “beep.” Keep the repeated job tiny.
range(3) gives the loop three turns.
A good beginner loop has a clear ending. It does not spin forever.
for turn in range(3):beepbeepbeepdone!STEP BY STEP
A loop has a box that changes on every turn.
for turn in range(3):turn is a box. range(3) fills it with 0, then 1, then 2. print(turn)The indented line repeats. It shows what is in the box now.print("done")Not indented, so it runs once, after the loop ends.snacks = ["apple", "pear", "grape"]A list box, like in Boxes of all kinds. It has 3 spaces.for snack in snacks:snack takes each item of the list, one turn at a time. print("I like", snack)Repeats 3 times, once for each item: apple, pear, grape. print(turn)012done!Computers start counting at 0. range(3) gives 0, 1, 2. That is still three turns.
The word after for is a box. It gets a new value on every turn.
Lines pushed right repeat on every turn. Lines on the left run once.
KEEP A COUNT
stars = 0Start with an empty count: 0 stars.for turn in range(4):Four turns. stars = stars + 1Each turn, take what is in the box and add 1: 1, 2, 3, 4.print(stars)Runs once at the end and shows 4.RUN IT
Guess first. Then run real Python and check.
for turn in range(3):
print("beep")How many times will PyBot beep?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Change 3 to another small number, like 5. Run again and count the beeps.
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
for turn in range(3):
print("beep")How many beeps appear?
for star in range(2):
print("★")What does the loop repeat?
for light in range(4):
print("light")When is the loop finished?
for turn in range(3):
print(turn)Which number shows first?
colors = ["red", "blue"]
for color in colors:
print(color)How many turns does the loop take?
for turn in range(5):
print("hop")
print("rest")How many times does the last word show?
stars = 0
for turn in range(3):
stars = stars + 2
print(stars)What does Python show?
The step to repeat must be inside the loop. Move it in with spaces.
Beep Beep BeepOUTPUT
Want a fresh start? Clear only this page.
Next: a loop that asks a question before every turn.