← Intro to programming with Python

Using modules: math

import gives you tools other people already wrote.

Start this lesson

Python comes with a large collection of ready-made tools, organised into modules. Instead of writing your own square root function, you write import math at the top of your program and use math.sqrt(). The dot means "the sqrt tool from the math module". Modules keep Python tidy: you only load the tools you need, and you reuse code that thousands of people have already tested.

import math

print(math.sqrt(49))      # 7.0
print(math.pi)            # 3.141592653589793
print(math.ceil(4.1))     # 5  (round UP)
print(math.floor(4.9))    # 4  (round DOWN)
radius = 3
print(round(math.pi * radius ** 2, 2))   # area of a circle: 28.27

ceil always goes up to the next whole number and floor always goes down. They are handy for questions like "how many buses do we need?"

Common mistake: forgetting import math. Then math.sqrt gives a NameError: name 'math' is not defined.

Another: writing sqrt(49) without math. in front. The tool lives inside the module, so you must name the module.

You can also write from math import sqrt and then use sqrt(49) directly.