python · level 2 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
borrows a full of ready-made tools.
Python comes with hundreds of modules, together called the . Each module is a toolbox for one job: maths, dates, chance, files and more. Nobody has to write a square root function twice.
Write import math at the top of your program. Then reach inside with a dot: math.sqrt(81) is the square root of 81, and math.pi is pi.
math.ceil rounds up to the next whole number and math.floor rounds down, which helps when you cannot buy half a box.
import math
print(math.sqrt(81))
print(math.pi)
guests = 23
per_table = 6
print(math.ceil(guests / per_table))
print(math.floor(7.9)) Put every import at the top, so readers can see which toolboxes you use.
guess first
Paint for a wall. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import math
wall = 23
per_tin = 10
print(wall / per_tin)
print(math.ceil(wall / per_tin))
print(math.floor(wall / per_tin))
your turn
Your turn. Find the shortcut across a field.
Type the two side lengths of a rectangular field, in metres. Then fill in the math function that finds a square root, to get the distance corner to corner.
fix it
The pizza planner has never heard of maths. Fix it!
- Read the error: NameError. Which name has Python never heard of?
mathis a module, and Python only knows it after you import it.- Add import math as the very first line, then run.
nailed it
you borrowed from the standard library. :D
import mathloads a module from the standard library.- Reach inside a module with a dot:
math.sqrt(81). math.ceilrounds up andmath.floorrounds down.
new words in your collection
- module
- import
- standard library
This lesson isn’t saved. A free account remembers every lesson you finish.