for Loops and range()

Why loops?

Imagine printing Hello 100 times. You could write 100 print() lines… or use a loop, which repeats code for you.

Counting with range()

for i in range(5):
    print("Hello", i)

Output

Hello 0
Hello 1
Hello 2
Hello 3
Hello 4

How it works:

  • range(5) produces the numbers 0, 1, 2, 3, 4 (five numbers, starting from 0).
  • Each time round the loop, the next number is stored in i.
  • The indented block runs once for each number.

Think of it like this: A for loop is like a teacher calling the register: for each student in the class, call their name. Same action, repeated for every item.

Choosing where to start and stop

CodeNumbers
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 11, 2)0, 2, 4, 6, 8, 10 (step of 2)
range(5, 0, -1)5, 4, 3, 2, 1 (counting down)
for n in range(5, 0, -1):
    print(n)
print("Lift off!")

Output

5
4
3
2
1
Lift off!

Remember: The stop number is not included. range(1, 6) stops at 5.

Looping over a string

A for loop can go through anything that holds several items – like the letters of a word:

for letter in "Code":
    print(letter)

Output

C
o
d
e

Building a total

A very common pattern: start a variable at 0 and add to it inside the loop.

total = 0
for number in range(1, 11):
    total += number
print("1 + 2 + ... + 10 =", total)

Output

1 + 2 + ... + 10 = 55
HOME LEARN COMMUNITY DASHBOARD