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// B2.2 · ~29 min · Beginner
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.
Warm-up · Activity 1 of 7
i = 0
while i < 3:
print(i, end=" ")
i = i + 1Predict · Activity 2 of 7
total = 0
for n in [3, 5, 7]:
total = total + n
print(total)Practice · Activity 3 of 7
for i in range(1, ____):
print(i, end=" ")Practice · Activity 4 of 7
Practice · Activity 5 of 7
names = ["Ada", "Linus", "Guido"]
for number, name in enumerate(names, start=1):
if name == "Linus":
print(number)Brain teaser · Activity 6 of 7
numbers = [1, 2, 2, 3]
for n in numbers:
if n == 2:
numbers.remove(n)
print(numbers)Apply · Activity 7 of 7
Check your work against this list
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 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.pyOutput
1 bread 2.49
2 milk 1.19
3 apples 3.5
4 coffee 6.99
Items: 4
Total: 14.17
Checked: bread
Checked: applesTab 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.
Exercise 1 of 3
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.
Loop with for i in range(…) and add i to total inside the loop.
range stops before its stop value. Which stop makes the last i equal to n?
for i in range(1, n + 1): total = total + i
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)
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.pyRun the checks (needs learnrun.py in the same folder):
python learnrun.py testDownload learnrun.pyExercise 2 of 3
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.
range(start, stop, step) with a step of -1 counts down.
The stop is not included, so to end at 1 the stop has to be 0.
for i in range(n, 0, -1): print(i), then print("liftoff") after the loop, not indented.
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")
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.pyRun the checks (needs learnrun.py in the same folder):
python learnrun.py testDownload learnrun.pyExercise 3 of 3
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.
for letter in word: gives you one character per round.
letter in "aeiouAEIOU" is True when the letter is one of those characters.
Inside the loop: if letter in "aeiouAEIOU": count = count + 1
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)
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.pyRun the checks (needs learnrun.py in the same folder):
python learnrun.py testDownload learnrun.pynames = ["Ada", "Linus"]
for i in range(1, len(names) + 1):
print(names[i])
What Python prints
IndexError: list index out of rangeWhy, 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.
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.
for i in 5:
print(i)
What Python prints
TypeError: 'int' object is not iterableWhy, 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
5 questions, no hints. Score 80% or more to complete the lesson.
Finish every activity above to unlock the exit ticket.