Modules and the Standard Library
Reuse ready-made code with import
import. It is like opening a toolbox full of tools someone already built for you.
- explain what a module and the standard library are,
- use
importto bring in code others wrote, - use the
mathmodule (likemath.sqrtandmath.pi), - use the
randommodule (likerandom.randintandrandom.choice).
1. What is a module?
A module is a file full of ready-made Python code — useful functions and values that someone already wrote and tested. The standard library is the big set of modules that comes with Python automatically. You do not download anything; it is already there.
To use a module, you write import and the module's name at the top of your program:
import math
print(math.sqrt(16))
print(math.pi)
Output:
4.0
3.141592653589793
Here import math brings in the math module. Then math.sqrt(16) asks the module for a square root, and math.pi gives us the value of pi. The dot (.) means "look inside math for this thing".
2. How import works
First you ask for a module with import. Python finds it in the standard library and loads it. After that, everything inside the module is ready for you to use, again and again.