Warm-up · Activity 1 of 7
// B1.2 · ~25 min · Beginner
Numbers: Python as a calculator
After this lesson you can use Python as a calculator: work with whole and decimal numbers, divide in three different ways, get the order of operations right, and store and round results.
Predict · Activity 2 of 7
Predict before you read on: three ways of dividing 7 by 2. What does this print?
print(7 / 2, 7 // 2, 7 % 2)Practice · Activity 3 of 7
Fill in the operator so that the line prints 2 to the power of 10, which is 1024.
print(2 ____ 10)print(2 10)Practice · Activity 4 of 7
What does this print?
print(2 + 3 * 4, (2 + 3) * 4)Practice · Activity 5 of 7
Match each expression to the value Python gives.
Brain teaser · Activity 6 of 7
Brain teaser. What does this print?
print(-3 ** 2)Apply · Activity 7 of 7
Mini-task. A car drove distance = 523 km and used litres = 38.4 litres of fuel. Put both variables at the top of a program, then print the fuel use per 100 km, rounded to one decimal place. Change the two numbers and check the result with a calculator.
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
Trip conversions
A trip to the United States needs two conversions: a temperature from °C to °F (multiply by 9, divide by 5, add 32), and the marathon distance of 42.195 km into miles (one mile is 1.609344 km). The program stores the inputs in variables, calculates, and rounds. Change celsius and run it again.
main.py
# Convert a temperature and a distance for a trip to the US.
celsius = 21
km = 42.195
fahrenheit = celsius * 9 / 5 + 32
miles = km / 1.609344
print("Temperature:", fahrenheit, "°F")
print("Marathon:", round(miles, 2), "miles")
print("Whole miles:", km // 1.609344)
Run it with
python main.pyOutput
Temperature: 69.8 °F
Marathon: 26.22 miles
Whole miles: 26.0- celsius * 9 / 5 + 32: * and / come first, from left to right, and + comes last.
- fahrenheit is a float, 69.8, because / always gives a float.
- round(miles, 2) keeps two decimal places: 26.22.
- // throws away the fractional part, but with a float it still gives a float: 26.0.
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 2
Minutes into hours
A film lasts minutes = 135. Print its length in hours and minutes, like this: 2 h 15 min. Use // for the whole hours and % for the minutes left over. The checks also change the number at the top, so calculate with the variable.
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
Hint 1
minutes // 60 gives the whole hours: 135 // 60 is 2.
Hint 2
minutes % 60 gives what is left after those hours: 135 % 60 is 15.
Hint 3
print(minutes // 60, "h", minutes % 60, "min")
Show a solution
One way to solve it. Yours can look different and still pass the checks.
minutes = 135
print(minutes // 60, "h", minutes % 60, "min")
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
minutes = 135
# Print the whole hours and the minutes left over, e.g. 2 h 15 min
print(minutes / 60, "h")
test_main.py
import re
from learnrun import run_main
def run_with(**values):
with open("main.py", encoding="utf-8") as f:
code = f.read()
for name, value in values.items():
code, count = re.subn(rf"^{name} = .*$", f"{name} = {value!r}", code, count=1, flags=re.M)
assert count == 1, f"main.py needs the line {name} = ... at the top"
with open("variant.py", "w", encoding="utf-8") as f:
f.write(code)
return run_main(path="variant.py").strip()
def test_135():
"""135 minutes are 2 h 15 min"""
got = run_with(minutes=135)
assert got == "2 h 15 min", f"for 135 the program printed {got!r}, expected '2 h 15 min'"
def test_under_an_hour():
"""59 minutes are 0 h 59 min"""
got = run_with(minutes=59)
assert got == "0 h 59 min", f"for 59 the program printed {got!r}, expected '0 h 59 min'"
def test_whole_hours():
"""600 minutes are 10 h 0 min"""
got = run_with(minutes=600)
assert got == "10 h 0 min", f"for 600 the program printed {got!r}, expected '10 h 0 min'"
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 2
Splitting a bill
total = 50 euros is split between people = 3. Print what each person pays, rounded to two decimal places: Each pays: 16.67. The checks also try other totals and group sizes.
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
Hint 1
total / people gives each share, but with many decimal places: 16.666666666666668.
Hint 2
round(value, 2) keeps two decimal places.
Hint 3
print("Each pays:", round(total / people, 2))
Show a solution
One way to solve it. Yours can look different and still pass the checks.
total = 50
people = 3
print("Each pays:", round(total / people, 2))
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
total = 50
people = 3
# Print each share, rounded to 2 decimal places.
print("Each pays:", total / people)
test_main.py
import re
from learnrun import run_main
def run_with(**values):
with open("main.py", encoding="utf-8") as f:
code = f.read()
for name, value in values.items():
code, count = re.subn(rf"^{name} = .*$", f"{name} = {value!r}", code, count=1, flags=re.M)
assert count == 1, f"main.py needs the line {name} = ... at the top"
with open("variant.py", "w", encoding="utf-8") as f:
f.write(code)
return run_main(path="variant.py").strip()
def test_three_people():
"""50 euros for 3 people is 16.67 each"""
got = run_with(total=50, people=3)
assert got == "Each pays: 16.67", f"the program printed {got!r}, expected 'Each pays: 16.67'"
def test_even_split():
"""100 euros for 8 people is 12.5 each"""
got = run_with(total=100, people=8)
assert got == "Each pays: 12.5", f"for 100 and 8 the program printed {got!r}, expected 'Each pays: 12.5'"
def test_other_numbers():
"""20 euros for 3 people is 6.67 each"""
got = run_with(total=20, people=3)
assert got == "Each pays: 6.67", f"for 20 and 3 the program printed {got!r}, expected 'Each pays: 6.67'"
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.pyCommon mistakes
Writing multiplication as in maths
print(2(3 + 4))
What Python prints
TypeError: 'int' object is not callableWhy, and the fix
In maths, 2(3 + 4) means 2 times (3 + 4). In Python, a name or value followed by parentheses is a call, as in print(...), and a number cannot be called. Before the error, Python even warns: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma? Always write the *: 2 * (3 + 4).
Dividing by zero
people = 0
print(50 / people)
What Python prints
ZeroDivisionError: division by zeroWhy, and the fix
Division by zero has no result, so Python stops with an error instead of printing a number. The same goes for // and %. Make sure the number you divide by cannot be 0; later in the course you will learn to check it with if before dividing.
Using a variable before it has a value
print(total)
total = 5
What Python prints
NameError: name 'total' is not definedWhy, and the fix
Python runs a program from top to bottom, so on line 1 total does not exist yet. Assign a variable before the first line that uses it. A typo in the name gives the same error.
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.