Lesson 19 of 35Python
Python · Lesson 19 · 25 minutes
Modules – ready-made toolboxes
What you'll learn
- Import modules like math and random
- Tell import, from … import and as apart
- Write and use your own module
Don’t build everything yourself
Python comes with hundreds of ready-made modules – toolboxes for maths, randomness, time, files and much more. With import you bring one of them into your program:
import math
print(math.pi)
print(math.sqrt(81))
print(math.floor(3.9), math.ceil(3.1))Three ways to import
import random # whole module: random.randint(...)
from math import sqrt # just one function: sqrt(...)
import datetime as dt # with a short name: dt.date.today()
print(random.randint(1, 6))
print(sqrt(16))
print(dt.date(2026, 12, 24).weekday())| Notation | Call afterwards |
|---|---|
import math | math.sqrt(9) |
from math import sqrt | sqrt(9) |
import math as m | m.sqrt(9) |
Randomness with random
random is perfect for games:
import random
dice = [random.randint(1, 6) for _ in range(5)]
print("Roll:", dice)
print("Winner:", random.choice(["Mia", "Ben", "Lea"]))Your own module
A module is simply a .py file. Here we write one – and import it straight away:
with open("tools.py", "w") as file:
file.write("def greeting(name):\n return f'Hello {name}!'\n")
import tools
print(tools.greeting("Codelix"))Remember: In the browser you get the modules of Python’s standard library. Extra packages like
numpywould have to be installed separately.
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
import math
print(math.sqrt(16), math.floor(3.7))Your task
Your turn
Import the function sqrt and the number pi from the module math. Write a function circle_area(r) that returns the area of a circle (π · r²), and a function diagonal(a, b) that uses Pythagoras' theorem to calculate the diagonal of a rectangle (√(a² + b²)).
# Import sqrt and pi from math here
def circle_area(r):
pass
def diagonal(a, b):
pass
print(round(circle_area(2), 2))
print(diagonal(3, 4))- Something to think about
Write from math import sqrt, pi at the very top.
- Which command helps?
Area
=pi*r**2 – and give it back withreturn.Diagonal
=sqrt(a ** 2 + b ** 2) - Gap code – fill in the ___
___ def circle_area(r): return ___ def diagonal(a, b): return ___ print(round(circle_area(2), 2)) print(diagonal(3, 4))
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
from math import sqrt, pi
def circle_area(r):
return pi * r ** 2
def diagonal(a, b):
return sqrt(a ** 2 + b ** 2)
print(round(circle_area(2), 2))
print(diagonal(3, 4))