Importing Modules
A module is a file of Python code that you can use in your own program. Python comes with many built-in modules, for math, dates, files and many other tasks. Together they are called the standard library.
| Form | How a name is used |
|---|---|
import math | math.sqrt(16) |
import math as m | m.sqrt(16) |
from math import sqrt | sqrt(16) |
import math
print(math.sqrt(16))
print(math.ceil(2.3))
print(math.floor(2.7))
Output:
4.0
3
2
With import math, you write math. before each name. This makes it clear that sqrt, ceil and floor come from the math module. ceil rounds a number up to the next whole number, and floor rounds it down.
Imports usually go at the top of a file. Avoid a star import such as from math import *. It hides where each name came from, and it can replace names that already exist in your program.
Before you write a common tool yourself, check if the standard library already has it.
Round a decimal down and up with two math functions.