Skip to content
aviral gupta

// B2.2 · ~29 min · Beginner

for loops and range()

After this lesson you can loop over a list or a string with for, count with range(start, stop, step), number items with enumerate, and change a list safely while you loop.

Lesson 2 of 5 in B2 Control flow

You will be able to

  • Loop over the items of a list or a string with for
  • Produce number sequences with range(start, stop, step), knowing that stop is left out
  • Number items with enumerate, and loop over a copy when the loop changes the list
  1. Warm-up · Activity 1 of 7

    Warm-up from B1.5: what does this while loop print?

    i = 0
    while i < 3:
        print(i, end=" ")
        i = i + 1
  2. Predict · Activity 2 of 7

    Predict before you read on: what does this print?

    total = 0
    for n in [3, 5, 7]:
        total = total + n
    print(total)
  3. Practice · Activity 3 of 7

    Fill in the stop value so that the loop prints 1 2 3 4 5.

    for i in range(1, ____):
        print(i, end=" ")
    for i in range(1, ):
  4. Practice · Activity 4 of 7

    Match each range to the numbers it produces.

  5. Practice · Activity 5 of 7

    enumerate numbers the items. What does this print?

    names = ["Ada", "Linus", "Guido"]
    for number, name in enumerate(names, start=1):
        if name == "Linus":
            print(number)
  6. Brain teaser · Activity 6 of 7

    Brain teaser. numbers.remove(n) deletes the first item equal to n from the list. What does this print?

    numbers = [1, 2, 2, 3]
    for n in numbers:
        if n == 2:
            numbers.remove(n)
    print(numbers)
  7. Apply · Activity 7 of 7

    Mini-task. Write a program that reads a number with int(input()) and prints its multiplication table from 1 to 10, one line each, such as 7 x 3 = 21. Use a for loop over range, and check that the last line is the 10th.

    Check your work against this list

Build it yourself

Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.

Worked example

A shopping receipt

A receipt lists the items and prices of one shopping trip, in two lists with the same order. The program numbers each line with enumerate, adds up the total, and then uses range with a step to spot-check every second item. Change the lists at the top and run it again.

main.py

# Items and their prices, in the same order.
items = ["bread", "milk", "apples", "coffee"]
prices = [2.49, 1.19, 3.5, 6.99]

total = 0.0
for number, item in enumerate(items, start=1):
    price = prices[number - 1]
    print(number, item, price)
    total = total + price

print("Items:", len(items))
print("Total:", round(total, 2))

# Every second item, from the first: range with a step.
for i in range(0, len(items), 2):
    print("Checked:", items[i])

Run it with

python main.py

Output

1 bread 2.49
2 milk 1.19
3 apples 3.5
4 coffee 6.99
Items: 4
Total: 14.17
Checked: bread
Checked: apples
  • enumerate(items, start=1) numbers the lines from 1, so the price sits at position number - 1.
  • round(total, 2) tidies the float sum; adding floats can leave tiny rounding errors.
  • range(0, len(items), 2) gives 0 and 2: the stop, 4, is never included.
  • The two print lines after the first loop are not indented, so they run once.
Change it and run it

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Exercises

Exercise 1 of 3

Add up 1 to n

The program reads a whole number n. Print the sum 1 + 2 + … + n, using a for loop over range. For 5 it prints 15, for 100 it prints 5050, and for 0 it prints 0. Make sure n itself is included.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    Loop with for i in range(…) and add i to total inside the loop.

  2. Hint 2

    range stops before its stop value. Which stop makes the last i equal to n?

  3. Hint 3

    for i in range(1, n + 1): total = total + i

Show a solution

One way to solve it. Yours can look different and still pass the checks.

n = int(input())

total = 0
for i in range(1, n + 1):
    total = total + i
print(total)
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

n = int(input())

total = 0
# Add every number from 1 to n to total.
print(total)

test_main.py

from learnrun import run_main


def total_for(n):
    return run_main(f"{n}\n").strip()


def test_five():
    """1 to 5 adds up to 15"""
    got = total_for(5)
    assert got == "15", f"for 5 the program printed {got!r}, expected '15'"


def test_hundred():
    """1 to 100 adds up to 5050"""
    got = total_for(100)
    assert got == "5050", f"for 100 the program printed {got!r}, expected '5050' (is n itself included?)"


def test_zero_and_one():
    """0 gives 0 and 1 gives 1"""
    got = total_for(0), total_for(1)
    assert got == ("0", "1"), f"for 0 and 1 the program printed {got!r}, expected ('0', '1')"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Exercise 2 of 3

Countdown

The program reads a whole number n. Count down from n to 1, one number per line, and then print liftoff. Use range with a negative step. For 3 it prints 3, 2, 1 and liftoff on four lines; for 0 it prints only liftoff.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    range(start, stop, step) with a step of -1 counts down.

  2. Hint 2

    The stop is not included, so to end at 1 the stop has to be 0.

  3. Hint 3

    for i in range(n, 0, -1): print(i), then print("liftoff") after the loop, not indented.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

n = int(input())

for i in range(n, 0, -1):
    print(i)
print("liftoff")
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

n = int(input())

# Print n, n - 1, ..., 1 on separate lines.
print("liftoff")

test_main.py

from learnrun import run_main


def countdown(n):
    return run_main(f"{n}\n").split()


def test_three():
    """3 counts 3, 2, 1, liftoff"""
    got = countdown(3)
    assert got == ["3", "2", "1", "liftoff"], f"for 3 the program printed {got!r}"


def test_ends_at_one():
    """The countdown stops at 1, not 0"""
    got = countdown(5)
    assert got == ["5", "4", "3", "2", "1", "liftoff"], f"for 5 the program printed {got!r}"


def test_zero():
    """0 prints only liftoff"""
    got = countdown(0)
    assert got == ["liftoff"], f"for 0 the program printed {got!r}, expected ['liftoff']"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Exercise 3 of 3

Count the vowels

The program reads one word. Print how many of its letters are vowels: a, e, i, o or u, in lower or upper case. Loop over the string with for, and test each letter with in "aeiouAEIOU". For banana it prints 3; for rhythm it prints 0.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    for letter in word: gives you one character per round.

  2. Hint 2

    letter in "aeiouAEIOU" is True when the letter is one of those characters.

  3. Hint 3

    Inside the loop: if letter in "aeiouAEIOU": count = count + 1

Show a solution

One way to solve it. Yours can look different and still pass the checks.

word = input()

count = 0
for letter in word:
    if letter in "aeiouAEIOU":
        count = count + 1
print(count)
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

word = input()

count = 0
# Count the vowels in word.
print(count)

test_main.py

from learnrun import run_main


def vowels(word):
    return run_main(f"{word}\n").strip()


def test_banana():
    """banana has 3 vowels"""
    got = vowels("banana")
    assert got == "3", f"for banana the program printed {got!r}, expected '3'"


def test_no_vowels():
    """rhythm has none"""
    got = vowels("rhythm")
    assert got == "0", f"for rhythm the program printed {got!r}, expected '0'"


def test_upper_case():
    """Upper-case vowels count too: Eerie has 4"""
    got = vowels("Eerie")
    assert got == "4", f"for Eerie the program printed {got!r}, expected '4'"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Common mistakes

Counting indexes from 1

names = ["Ada", "Linus"]
for i in range(1, len(names) + 1):
    print(names[i])

What Python prints

IndexError: list index out of range

Why, and the fix

List indexes run from 0 to len(names) - 1, so range(1, len(names) + 1) asks for one position too many. Loop over the items directly, for name in names:, or use enumerate(names, start=1) when you want to show numbers from 1.

Forgetting the colon

for n in [1, 2, 3]
    print(n)

What Python prints

SyntaxError: expected ':'

Why, and the fix

Like if, a for line ends with a colon, and the indented block under it is the loop body: for n in [1, 2, 3]:. Python stops before running anything and points at the end of the line.

Looping over a number

for i in 5:
    print(i)

What Python prints

TypeError: 'int' object is not iterable

Why, and the fix

for needs something with items, such as a list, a string or a range. A plain number has no items. To repeat five times, write for i in range(5):.

Python in the browser: Pyodide 314.0.7, MPL-2.0. Licence and source

Exit ticket

5 questions, no hints. Score 80% or more to complete the lesson.

Finish every activity above to unlock the exit ticket.

Report a problem

Spotted something wrong or unclear? Say what, and it will be checked and fixed.

#

At least 20 characters.

Only if you want a reply.

Key ideas

for takes the items one by one

for item in items: runs its indented block once for every item of a sequence, in order. On each round the name item holds the next value: the next element of a list, or the next character of a string. You do not manage an index or a condition as with while, so the loop cannot run forever or skip an item by mistake. After the loop, the name still holds the last item. Use while when you do not know in advance how often to repeat; use for when you walk through a collection.

range counts for you

range(stop) gives 0, 1, … up to stop − 1: range(5) is 0 to 4, five numbers. range(start, stop) starts somewhere else, and range(start, stop, step) jumps by step, which can be negative: range(10, 0, -2) is 10, 8, 6, 4, 2. The stop value is never part of the sequence. A range is not a list: print(range(3)) shows range(0, 3). To see the numbers, loop over it or write list(range(3)). range(5, 1) is empty, because counting up from 5 never reaches 1.

enumerate, and changing a list while looping

enumerate(items) gives pairs of position and item, and for i, item in enumerate(items): unpacks each pair into two names. Positions start at 0; enumerate(items, start=1) counts from 1, which reads better on screen. Avoid removing items from the list you are looping over: the loop moves on by position, so the item after a removed one is skipped. Loop over a copy instead, for n in numbers[:], or build a new list with append.

Sources

Last reviewed September 29, 2026