Library Modules#
Note
Source: Drawn from the SE4ML Python chapter (chapter_python.rst,
lines 563–683). The math module table, random module examples,
and from … import forms closely follow the SE4ML presentation.
Writing-your-own-module example is an original addition.
Python’s strength comes partly from its enormous standard library and
ecosystem of third-party packages. A module is a .py file containing
functions and variables you can use in your own programs.
Importing a Module#
Use the import statement to make a module available:
import math
After importing, access the module’s contents with dot notation:
>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> math.pi
3.141592653589793
>>> math.floor(3.7)
3
>>> math.ceil(3.2)
4
The math Module#
The math module provides mathematical functions beyond what is built in:
Function / Constant |
Description |
|---|---|
|
Square root of |
|
The constant π ≈ 3.14159… |
|
The constant e ≈ 2.71828… |
|
Largest integer ≤ |
|
Smallest integer ≥ |
|
Natural logarithm of |
|
Logarithm of |
|
Trigonometric functions ( |
|
Convert radians to degrees |
|
Convert degrees to radians |
|
n! |
The random Module#
The random module generates pseudo-random numbers, which is useful for
games and simulations:
>>> import random
>>> random.randint(1, 6) # simulates a die roll
4
>>> random.random() # float in [0.0, 1.0)
0.37444887175646646
>>> random.choice(["rock", "paper", "scissors"])
'paper'
Selective Import#
To import just specific names from a module, avoiding the module prefix:
from math import sqrt, pi
print(sqrt(2)) # no 'math.' needed
print(pi)
Or import everything (generally discouraged in larger programs):
from math import *
You can also give a module a shorter alias:
import math as m
print(m.sqrt(2))
How Python Finds Modules#
When you write import math, Python looks for a module named math.py
in a list of directories called the path. The standard library is always on
the path, so built-in modules like math and random are always
available.
When you create your own .py files, Python can import them if they are in
the same directory as your script.
Writing Your Own Module#
Any .py file can be used as a module. If you save the following in
geometry.py:
import math
def circle_area(radius):
return math.pi * radius ** 2
def circle_circumference(radius):
return 2 * math.pi * radius
Then another file can use it:
import geometry
print(geometry.circle_area(5))