Board Formulas
🐍 PythonπŸ“… Day 15

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)

#1Three ways to import
python
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))
Output
12.0
3.1416 120
1024.0
The first form keeps the module name, so it is always clear where sqrt comes from. Note that sqrt() and pow() return floats.
#2The math module
python
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))
Output
5 4
7.5
12
Area: 153.94
0.49999999999999994
0.5
ceil rounds up, floor rounds down. Trig functions expect radians, and floating-point results can be a tiny bit off, so round them for display.
#3The random module
python
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)
Output
3
12
0.395
Amit
[3, 4, 2, 5, 1]
Without seed() you get different values every run. The output shown is from Python 3.12; other versions may give different numbers for the same seed.
#4The statistics module
python
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))
Output
Mean: 76.67
Median: 78.5
Mode: 85
With an even number of values, the median is the average of the two middle ones: (72 + 85) / 2 = 78.5. The mode is the most common value.
#5Writing your own module
python
# 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)
Output
82.4% - Pass
Pass mark: 33
Save the two files in the same folder and run report.py. The output is what report.py prints. The module name is the file name without .py.
#6if __name__ == '__main__'
python
# 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__)
Output
Namaste, Priya!
__main__
Running main.py imports greet.py, so its test line is skipped. Run python3 greet.py directly and you would see Namaste, Test! instead.

🎯 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 .py file 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, plain sqrt(4) raises NameError. Write math.sqrt(4).
  • Off-by-one with random: randint(1, 6) includes 6, but randrange(1, 6) stops at 5.
  • Degrees in trig functions: math.sin(30) treats 30 as radians. Convert with math.radians(30) first.

Next: Day 16 β€” Exception Handling, so your programs survive bad input instead of crashing.