Modules and import
math, random and your own modules.
Python comes with a large standard library: modules for maths, dates, text, archives and networking. A module is brought in with import:
import math
print(math.sqrt(16), math.ceil(4.1)) # 4.0 5
from math import pi
print(round(pi, 2)) # 3.14
ceil rounds up, floor rounds down, to the smaller whole number. import math gives access through the math. prefix, and from math import pi brings in a single name directly. The prefix is useful: math.sqrt shows at once where the function comes from.
random produces pseudo-random numbers: random.randint(1, 6) is a dice roll, random.choice(items) a random element. To make the result repeatable, for example in tests, you set the starting value: random.seed(42). With the same seed the sequence of numbers is always the same. random is not suitable for passwords and tokens: there is the secrets module for that.
Any .py file of yours is a module too. Functions from utils.py can be used in another file with import utils. Code that should run only when the file is started directly, not when it is imported, goes under a check:
if __name__ == "__main__":
main()
Third-party libraries are installed with the pip package manager from the official PyPI index, usually into the project's virtual environment (python -m venv .venv). That way the dependencies of different projects do not get in each other's way. In the learning sandbox only the standard library modules needed for the tasks are available.
Practice
Which way is down
What does the program print?
import math print(math.floor(-2.5))Why seed
Why is random.seed(42) called in tests?
- So that the random numbers repeat from run to run
- So that the numbers become cryptographically secure
- So that random works faster
- random does not work without a seed
The hypotenuse
Write a function hypot(a, b) that returns the length of the hypotenuse of a right triangle with legs a and b, rounded to two digits. Use the math module.