← Python lessons

For Loops

A for loop runs the same block of code once for each item in a collection. It saves you from writing the same lines over and over.

Looping a set number of times

When you want to repeat something a fixed number of times, loop over range() instead of a list — see The range() function:

for i in range(3):
    print(i)

Optional: looping over a list

rolls = [3, 5, 2]
for roll in rolls:
    print(roll)

roll is a variable that takes each value in turn — first 3, then 5, then 2. The indented block runs once per item.

Optional: building up a result

Optional next step: The Accumulator Pattern shows how to build a total while a loop runs.

See also: Lists, The range() function, The accumulator pattern.

Your turn

Use a for loop to print Go! three times, once per line.

# Add a for loop using range(3).

Expected output

Go!
Go!
Go!

Optional extension after learning about lists: loop over [4, 2, 6] and print twice each value.


Practise this in the free Python course, where every exercise checks your code instantly.