Modules and Packages in Python
Reuse code with import, use the math, random and statistics modules, and write your own module and package.
Learning objectives
- βUse import, from ... import and import ... as correctly
- βUse common functions from the math, random and statistics modules
- βWrite your own module and import it into another program
- βUnderstand packages and the if __name__ == '__main__' check
π‘ Key points
- A module is simply a .py file. import lets one program use the functions and variables of another.
- import math β write math.sqrt(). from math import sqrt β write sqrt(). import math as m β write m.sqrt().
- Avoid from module import * β it dumps every name into your program and can silently replace your own variables.
- math: sqrt, pow, ceil, floor, fabs, factorial, gcd, pi, e, and sin/cos/tan (which take angles in radians).
- random: random() gives a float from 0.0 up to (not including) 1.0; randint(a, b) includes b; randrange(a, b) excludes b.
- statistics: mean(), median() and mode() work on any list of numbers.
- A package is a folder of modules, usually with an __init__.py file. Import from it with dots: from school import marks.
π» Code examples(6)
import math
print(math.sqrt(144))
from math import pi, factorial
print(round(pi, 4), factorial(5))
import math as m
print(m.pow(2, 10))
12.0 3.1416 120 1024.0
import math
print(math.ceil(4.2), math.floor(4.8))
print(math.fabs(-7.5))
print(math.gcd(24, 36))
r = 7
print(f"Area: {math.pi * r ** 2:.2f}")
angle = math.radians(30) # degrees β radians
print(math.sin(angle))
print(round(math.sin(angle), 2))
5 4 7.5 12 Area: 153.94 0.49999999999999994 0.5
import random
random.seed(7) # same 'random' numbers each run
print(random.randint(1, 6)) # 1 to 6
print(random.randrange(10, 20)) # 10 to 19
print(round(random.random(), 3)) # 0.0 to <1.0
print(random.choice(["Amit", "Priya", "Ravi"]))
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)
3 12 0.395 Amit [3, 4, 2, 5, 1]
import statistics as st
marks = [60, 72, 85, 90, 85, 68]
print("Mean:", round(st.mean(marks), 2))
print("Median:", st.median(marks))
print("Mode:", st.mode(marks))
Mean: 76.67 Median: 78.5 Mode: 85
# file: marks_util.py
"""Helper functions for student marks."""
PASS_MARK = 33
def percentage(obtained, total):
return obtained / total * 100
def result(pct):
return "Pass" if pct >= PASS_MARK else "Fail"
# file: report.py
import marks_util
p = marks_util.percentage(412, 500)
print(f"{p:.1f}% - {marks_util.result(p)}")
print("Pass mark:", marks_util.PASS_MARK)
82.4% - Pass Pass mark: 33
# file: greet.py
def greet(name):
return f"Namaste, {name}!"
if __name__ == "__main__":
# runs only when greet.py itself is run
print(greet("Test"))
# file: main.py
from greet import greet
print(greet("Priya"))
print(__name__)
Namaste, Priya! __main__
π― Practice
Q1. Write the import statement that lets you call sqrt(25) without the math. prefix.+
from math import sqrt
Q2. Which values can random.randint(1, 10) return? And random.randrange(1, 10)?+
randint(1, 10): any whole number from 1 to 10. randrange(1, 10): 1 to 9, because the stop value is excluded.
Q3. What is printed by: import math; print(math.ceil(-2.5), math.floor(-2.5))+
-2 -3. ceil goes up towards +infinity and floor goes down towards -infinity.
Q4. Why should you not save your own program as random.py?+
Python would import your file instead of the real random module, so import random followed by random.randint() fails with AttributeError.
Q5. Find the median of [3, 9, 1, 7] using the statistics module.+
import statistics print(statistics.median([3, 9, 1, 7])) # 5.0
π Notes
Exploring a module
You do not need to memorise every function. Ask Python:
import math
print(dir(math)) # every name inside math
help(math.floor) # documentation for one function
Packages
When a project grows, related modules are grouped in a folder called a package:
school/
__init__.py
marks.py
attendance.py
Use it with dots:
from school import marks
from school.marks import percentage
import school.attendance as att
The __init__.py file (which can be empty) marks the folder as a regular package and runs the first time the package is imported.
Where modules come from
- Built-in / standard library:
math,random,statistics,csv,pickleβ installed with Python. - Your own files: any
.pyfile in the same folder as your program. - Third-party packages: installed from PyPI with
pip install name.
Python checks your program's own folder before the standard library, so a file of yours can hide a standard module that has the same name.
Common mistakes
- Naming a file after a module (
random.py,csv.py,statistics.py): your file hides the real one. - Forgetting the prefix: after
import math, plainsqrt(4)raises NameError. Writemath.sqrt(4). - Off-by-one with random:
randint(1, 6)includes 6, butrandrange(1, 6)stops at 5. - Degrees in trig functions:
math.sin(30)treats 30 as radians. Convert withmath.radians(30)first.
Next: Day 16 β Exception Handling, so your programs survive bad input instead of crashing.