Importing a module
Python has a few dozen functions built in, such as print, len and sum. Everything else lives in modules: files of ready-made functions and values, grouped by theme. Python comes with a large collection of them, called the standard library: a module for mathematics, one for random numbers, one for dates, one for reading CSV files, and hundreds more. This part of the course takes a tour of the most useful ones, and ends with modules you write yourself.
import
A module's contents aren't available until you ask for them. The import command loads a module and gives your program access to it. The math module has mathematical functions and constants:
import math
print(math.sqrt(49))
print(math.pi)
print(math.floor(7.8))
print(math.ceil(7.2))
7.0
3.141592653589793
7
8After import math, the program reaches everything in the module through the module's name and a dot: math.sqrt is the function sqrt of the module math.
sqrtgives the square root of a number, always as a float.piisn't a function but a value stored in the module, so it has no parentheses.floorrounds down to a whole number, andceil(short for ceiling) rounds up.
Imports go at the top of a program, one module per line, so a reader sees at a glance which modules the program uses.
When rounding up is right
Rounding up is what you need whenever the leftovers still need a place of their own. Ten people in cars that seat four need three cars, not 2.5:
import math
people = 10
seats = 4
print("Cars needed:", math.ceil(people / seats))
Cars needed: 3The module's name is part of the name
With import math, the names in the module are reached only through math. in front of them. Writing just sqrt doesn't work:
import math
print(sqrt(16))
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(sqrt(16))
^^^^
NameError: name 'sqrt' is not definedAnd if the import line is missing, Python doesn't know the name math at all. Its message then suggests the fix itself: NameError: name 'math' is not defined. Did you forget to import 'math'?