Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 11

Python Modules

7 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A module is a Python file with reusable code.

You will learn how to import modules and use the standard-library modules math, os, random, statistics, sys and collections.

Modules let you reuse tested code instead of writing everything from scratch.

File handling scripts, simulations, data analysis, command-line tools.

1

Python Modules

A module is a file containing Python definitions (functions, classes, variables) and statements that can be imported into other programs. The file name without .py is the module name.

In short: A module is a toolbox in a file. import lets you borrow its tools.

Modules plug into your program

Think about it

The standard library has hundreds of modules, which saves enormous time. Instead of writing your own square-root code, import math and call math.sqrt.

Import forms: import math (use `math.

sqrt), import math as m (alias), from math import sqrt, pi (use names directly) and from math import *` (avoid: pollutes names).

Python searches the current folder, then the paths in `sys.

path`, then installed packages.

A module is executed once and cached in `sys.

modules`.

dir(module) lists its names and help(module) shows documentation.

Create your own module by saving functions in `mymodule.

py` in the same folder.

Every module has a __name__: it is "__main__" when run directly and the module name when imported, so if __name__ == "__main__": runs test code only when executed directly.

A package is a folder of modules (with `__init__.

py`).

Third-party modules are installed with pip install name.

Do not name your file the same as a standard module (e.

g.

`random.

py`) because it hides it.

Key points

  • import: Statement that loads a module.
  • Alias: Shorter name given with as.
  • Package: Folder of related modules.
  • __name__: Variable holding "__main__" when the file is run directly.

Example

Code
Importing and creating modules:
import math
print(math.sqrt(25))               # 5.0

import math as m
print(m.pi)                        # 3.141592653589793

from math import sqrt, floor
print(sqrt(49), floor(2.9))        # 7.0 2

print("sqrt" in dir(math))          # True
print(math.__name__)               # math

import sys
print(type(sys.path), "math" in sys.modules)   # <class 'list'> True

# ---- file: mytools.py ----
# def square(x):
#     return x * x
#
# if __name__ == "__main__":
#     print(square(4))     # runs only when: python mytools.py

# ---- another file ----
# import mytools
# print(mytools.square(5)) # 25 (the test block above is skipped)

# install a third-party module in the terminal:
#   pip install requests
2

Python Math Module

The math module provides mathematical functions and constants for real numbers, such as sqrt, ceil, floor, factorial, gcd, log, trigonometric functions, pi and e.

In short: math is the scientific calculator of Python.

Think about it

Used in nearly every numeric program and formula-based exam question. Calculating the area of a circle: math.pi * r ** 2.

Constants: `math.

pi, math.

e, math.

inf, math.

nan`.

Rounding: ceil (up), floor (down), trunc (towards zero); note floor(-4.2) is -5 while trunc(-4.2) is -4.

Powers and roots: sqrt, pow (always returns float), exp.

Logs: log(x) natural, log(x, base), log10, log2.

Trigonometry uses RADIANS: convert with radians() and degrees().

Integer helpers: factorial, gcd, lcm (3.9+), comb(n, k), perm(n, k), isqrt.

hypot(a, b) gives the hypotenuse.

Floating-point values are inexact, so compare with `math.

isclose(a, b) rather than ==`.

`math.

sqrt(-1)` raises ValueError (use cmath for complex numbers).

The module works with real numbers only.

Key points

  • Radian: Angle unit used by trigonometric functions (pi radians = 180 degrees).
  • ceil / floor: Round up / round down to an integer.
  • isclose: Compare floats with a tolerance.

Example

Code
Common math module functions:
import math

print(math.sqrt(16), math.pow(2, 3))        # 4.0 8.0
print(math.ceil(4.2), math.floor(4.8))      # 5 4
print(math.floor(-4.2), math.trunc(-4.2))   # -5 -4

print(math.factorial(5), math.gcd(12, 18))  # 120 6
print(math.lcm(4, 6), math.comb(5, 2))      # 12 10   (lcm needs 3.9+)

print(math.log(math.e), math.log10(1000), math.log2(8))   # 1.0 3.0 3.0
print(math.log(100, 10))                    # 2.0

print(math.sin(math.pi / 2))                # 1.0
print(math.degrees(math.pi), math.radians(180))   # 180.0 3.141592653589793
print(math.hypot(3, 4))                     # 5.0

print(0.1 + 0.2 == 0.3)                     # False
print(math.isclose(0.1 + 0.2, 0.3))         # True

r = 7
print(round(math.pi * r ** 2, 2))           # 153.94

print(math.inf > 10 ** 100)                 # True
try:
    math.sqrt(-1)
except ValueError as e:
    print(e)                                # math domain error
3

Python OS Module

The os module lets Python programs interact with the operating system: working with folders and files, reading environment variables and building file paths. os.path has helpers for path manipulation.

In short: os lets your program look around the computer and create, rename or delete files and folders.

Think about it

Automating file tasks (renaming, cleaning folders, reading config) is a core Python use. A script that renames all photos in a folder or deletes old log files.

Directories: `os.

getcwd() current folder, os.

chdir(path), os.

listdir(path), os.

mkdir(name), os.

makedirs("a/b/c", exist_ok=True) for nested folders, os.

rmdir(name)` for an empty folder.

Files: `os.

rename(old, new), os.

remove(file)`.

Path helpers in `os.

path: join (builds a path using the correct separator), exists, isfile, isdir, basename, dirname, splitext, getsize, abspath`.

Other: `os.

environ` (dict of environment variables, use `.

get), os.

name ("nt" on Windows, "posix" on Linux/Mac), os.

system(cmd) runs a shell command, os.

walk(top)` visits every folder recursively.

Always check with `os.

path.

exists before deleting, and prefer pathlib` for modern path code.

Deleting files cannot be undone, so test carefully.

Key points

  • Path: Text that describes where a file or folder is.
  • Environment variable: Setting stored by the OS, e.g. HOME or PATH.
  • os.walk: Generator that goes through a directory tree.

Example

Code
Working with folders, files and paths:
import os

print(os.getcwd())                      # current folder path
os.makedirs("demo/sub", exist_ok=True)  # create nested folders
print(os.path.exists("demo/sub"))       # True

path = os.path.join("demo", "notes.txt")   # correct separator for your OS
with open(path, "w") as f:
    f.write("hello")

print(os.listdir("demo"))               # ['notes.txt', 'sub']  (order may vary)
print(os.path.isfile(path), os.path.isdir("demo"))   # True True
print(os.path.getsize(path))            # 5
print(os.path.basename(path))           # notes.txt
print(os.path.splitext("report.final.pdf"))   # ('report.final', '.pdf')

os.rename(path, os.path.join("demo", "renamed.txt"))
os.remove(os.path.join("demo", "renamed.txt"))
os.rmdir("demo/sub")
os.rmdir("demo")

print(os.name)                          # nt on Windows, posix on Linux/Mac
print(os.environ.get("HOME", "not set"))

for folder, subfolders, files in os.walk("."):
    print(folder, len(files))
    break                               # show only the first folder
4

Python Random Module

The random module generates pseudo-random numbers and makes random choices, shuffles and samples. Examples: random, randint, randrange, uniform, choice, choices, shuffle, sample and seed.

In short: random is a digital dice and card shuffler.

Think about it

Needed for games, simulations, sampling data and creating test data. Rolling a die in a game: random.randint(1, 6).

`random.

random()` gives a float in [0.0, 1.0).

randint(a, b) includes BOTH ends.

randrange(start, stop, step) excludes stop like range.

uniform(a, b) gives a random float.

choice(seq) picks one item; choices(seq, k=3) picks k WITH replacement (repeats possible; supports weights); sample(seq, k) picks k UNIQUE items (without replacement); shuffle(lst) shuffles a list in place and returns None.

`random.

seed(n)` makes the sequence repeatable, which is good for tests.

The numbers are pseudo-random and NOT secure; use the secrets module for passwords and tokens.

shuffle does not work on tuples or strings; convert to a list first.

Key points

  • Pseudo-random: Generated by a formula; repeatable with the same seed.
  • Seed: Starting value that fixes the random sequence.
  • With replacement: The same item may be chosen again.

Example

Code
Random numbers, choices and shuffling:
import random

random.seed(42)                   # repeatable results
print(random.random() < 1)        # True  (value in [0.0, 1.0))
print(1 <= random.randint(1, 6) <= 6)     # True (both ends included)
print(random.randrange(0, 10, 2) in [0, 2, 4, 6, 8])   # True
print(1.5 <= random.uniform(1.5, 2.5) <= 2.5)          # True

colors = ["red", "green", "blue", "pink"]
print(random.choice(colors) in colors)      # True
print(random.choices(colors, k=3))          # 3 items, repeats allowed
print(random.sample(colors, 2))             # 2 unique items

cards = [1, 2, 3, 4, 5]
random.shuffle(cards)                       # in place, returns None
print(sorted(cards))                        # [1, 2, 3, 4, 5]

print(random.choices(["H", "T"], weights=[9, 1], k=5))   # mostly H

otp = "".join(str(random.randint(0, 9)) for _ in range(4))
print(len(otp))                             # 4

# for passwords use secrets, not random
import secrets
print(len(secrets.token_hex(8)))            # 16
5

Python Statistics Module

The statistics module calculates basic statistics of numeric data: mean, median, mode, variance and standard deviation.

In short: Give it a list of numbers and it tells you the average, the middle value and how spread out the numbers are.

Think about it

Quick data summaries are needed in school projects, analysis scripts and data-science basics. Finding the average, median and standard deviation of class test scores.

mean(data) is the arithmetic average.

median(data) is the middle value of the sorted data (for an even count it is the average of the two middle values).

median_low and median_high return an actual data point.

mode(data) returns the most frequent value (works for text too); multimode(data) returns a list of all modes.

Spread: pvariance / pstdev treat the data as the WHOLE population (divide by n), while variance / stdev treat it as a SAMPLE (divide by n-1) and need at least two values.

mean of an empty list raises StatisticsError.

fmean is a faster float version.

For big numerical arrays use NumPy, but this module is perfect for small lists and exams.

Key points

  • Mean: Sum divided by count.
  • Median: Middle value of sorted data.
  • Mode: Most frequent value.
  • Standard deviation: Typical distance of values from the mean.

Example

Code
Mean, median, mode and deviation:
import statistics as st

data = [2, 4, 4, 4, 5, 5, 7, 9]
print(st.mean(data))              # 5
print(st.median(data))            # 4.5   (average of 4 and 5)
print(st.mode(data))              # 4
print(st.multimode([1, 1, 2, 2])) # [1, 2]

print(st.pvariance(data))         # 4.0
print(st.pstdev(data))            # 2.0   (population)
print(round(st.stdev(data), 2))   # 2.14  (sample, divides by n-1)

print(st.median([3, 1, 2]))       # 2
print(st.median_low([1, 2, 3, 4]), st.median_high([1, 2, 3, 4]))   # 2 3
print(st.mode(["a", "b", "a"]))   # a

try:
    st.mean([])
except st.StatisticsError as e:
    print("empty data")
6

Python Sys Module

The sys module gives access to variables and functions related to the Python interpreter: command-line arguments (`sys.argv), module search path (sys.path), Python version, platform, standard input/output streams and sys.exit()`.

In short: sys is the control panel of the Python interpreter itself.

Think about it

Command-line tools, debugging, portability checks and memory checks all use sys. python add.py 3 4 reads the numbers from sys.argv and prints 7.

`sys.

argv` is a list of command-line arguments as STRINGS; argv[0] is the script name.

`sys.

exit(code)` ends the program (0 = success, non-zero = error) by raising SystemExit.

`sys.

version and sys.

version_info identify the Python version; sys.

platform names the OS ("win32", "linux", "darwin"`).

`sys.

path` is the list of folders searched for imports.

`sys.

modules` is the dict of loaded modules.

`sys.

stdin, sys.

stdout and sys.

stderr are the standard streams (sys.

stdout.

write` prints without adding a newline; errors go to stderr).

`sys.

getsizeof(obj)` gives the memory of an object in bytes (not including referenced objects).

`sys.

maxsize` is the largest native index size (2**63 - 1 on 64-bit).

`sys.

getrecursionlimit() and sys.

setrecursionlimit()` read and change the recursion limit.

Key points

  • argv: List of command-line arguments (strings).
  • Exit code: Number returned to the OS; 0 means success.
  • stdout / stderr: Normal output stream and error stream.

Example

Code
sys: version, streams, argv and exit:
import sys

print(sys.version_info.major >= 3)       # True
print(sys.platform)                      # win32 / linux / darwin
print(sys.maxsize == 2 ** 63 - 1)        # True on 64-bit Python
print(sys.getsizeof([]), sys.getsizeof(10))   # sizes in bytes (depends on version)
print(sys.getrecursionlimit())           # 1000 by default

sys.stdout.write("no newline added")
sys.stdout.write("\n")
sys.stderr.write("this goes to the error stream\n")

# ---- file: add.py ----
# import sys
# if len(sys.argv) != 3:
#     print("usage: python add.py A B")
#     sys.exit(1)               # non-zero = error
# a, b = int(sys.argv[1]), int(sys.argv[2])   # argv items are strings
# print(a + b)
#
# run:  python add.py 3 4     ->   7

print(sys.path[0] != "")                 # script folder is searched first

try:
    sys.exit(0)
except SystemExit as e:
    print("exit code", e.code)           # exit code 0
7

Python Collection Module

The collections module provides specialised container types that extend the built-in list, dict and tuple: Counter, defaultdict, deque, namedtuple, OrderedDict and ChainMap.

In short: collections gives you upgraded containers for common jobs like counting, grouping and queues.

Think about it

These containers replace many lines of manual code and appear often in interviews. Counting the most common words in a book with Counter, or implementing a task queue with deque.

`Counter(iterable) counts items and has most_common(n)`; missing keys give 0.

defaultdict(factory) creates a default value automatically for a missing key, e.

g.

defaultdict(list) for grouping and defaultdict(int) for counting.

deque is a double-ended queue with O(1) append, appendleft, pop, popleft and rotate; it is better than a list for queues because `list.

pop(0)` is O(n).

namedtuple("Point", ["x", "y"]) creates a tuple subclass with named fields (access by name or index, still immutable).

OrderedDict remembers insertion order (regular dicts do too now, but OrderedDict supports move_to_end and order-sensitive equality).

ChainMap searches several dictionaries as one.

A deque(maxlen=n) automatically drops old items, handy for "last n" history.

Key points

  • Counter: dict subclass that counts hashable items.
  • defaultdict: dict that supplies a default value for missing keys.
  • deque: Double-ended queue with fast operations at both ends.
  • namedtuple: Tuple whose items also have names.

Example

Code
Counter, defaultdict, deque, namedtuple:
from collections import Counter, defaultdict, deque, namedtuple, OrderedDict

c = Counter("banana")
print(c)                          # Counter({'a': 3, 'n': 2, 'b': 1})
print(c.most_common(1))           # [('a', 3)]
print(c["z"])                     # 0   (missing key is 0)

words = "to be or not to be".split()
print(Counter(words).most_common(2))   # [('to', 2), ('be', 2)]

groups = defaultdict(list)
for w in ["hi", "yo", "cat"]:
    groups[len(w)].append(w)
print(dict(groups))               # {2: ['hi', 'yo'], 3: ['cat']}

counts = defaultdict(int)
for ch in "aab":
    counts[ch] += 1
print(dict(counts))               # {'a': 2, 'b': 1}

dq = deque([1, 2, 3])
dq.append(4)                      # right end
dq.appendleft(0)                  # left end
print(dq)                         # deque([0, 1, 2, 3, 4])
print(dq.popleft(), dq.pop())     # 0 4
dq.rotate(1)
print(dq)                         # deque([3, 1, 2])

last3 = deque(maxlen=3)
for n in range(6):
    last3.append(n)
print(last3)                      # deque([3, 4, 5], maxlen=3)

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p[1], p)               # 3 4 Point(x=3, y=4)

od = OrderedDict(a=1, b=2)
od.move_to_end("a")
print(list(od))                   # ['b', 'a']

Counter

Counts frequency and returns most_common results.

defaultdict

Avoids KeyError and removes setdefault boilerplate.

deque

Fast queue and stack operations at both ends.

namedtuple

Readable records with field names.

Solved examples

Example 01 · Basic

Find the area of a circle with radius 5 rounded to 2 decimals using math.

Given Data:
    Required To Find:

    Area

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: import math
    Step 2: Use math.pi * r ** 2
    Step 3: Round to 2 places
    Final Answer: import math print(round(math.pi * 5 ** 2, 2)) # 78.54

    Approach note: Remember the module prefix: math.pi.

    Example 02 · Basic

    Find the three most common words in "a b a c b a".

    Given Data:
      Required To Find:

      Top words with counts

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Split the text into words
      Step 2: Counter(words)
      Step 3: most_common(3)
      Final Answer: Counter('a b a c b a'.split()).most_common(3) → [('a', 3), ('b', 2), ('c', 1)]

      Approach note: Counter gives the result without a manual loop.

      Example 03 · Intermediate

      Print the mean and median of [10, 20, 30, 40].

      Given Data:
        Required To Find:

        Two numbers

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: mean = 100 / 4 = 25
        Step 2: median = (20 + 30) / 2 = 25.0
        Final Answer: statistics.mean → 25, statistics.median → 25.0

        Approach note: For an even count the median is the average of the two middle values.

        Example 04 · Intermediate

        Pick 3 different random winners from ["A", "B", "C", "D", "E"].

        Given Data:
          Required To Find:

          Three unique names

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: sample picks without replacement
          Step 2: Pass the list and k=3
          Final Answer: random.sample(["A", "B", "C", "D", "E"], 3)

          Approach note: choices may repeat the same name; sample never does.

          Real-world applications

          Python

          Using Python Modules in real projects

          File handling scripts, simulations, data analysis, command-line tools.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: import math lets me call sqrt() directly.

          Why this is wrong: The module name is needed unless you use from math import sqrt.

          ✅ Verified Truth: Write math.sqrt(x).

          ⚠️ Exam Tip: Know all four import styles.

          ❌ Myth: random.randint(1, 6) never gives 6.

          Why this is wrong: randint includes both ends.

          ✅ Verified Truth: randrange(1, 6) is the one that excludes 6.

          ⚠️ Exam Tip: Compare randint vs randrange.

          ❌ Myth: sys.argv values are numbers.

          Why this is wrong: They are always strings.

          ✅ Verified Truth: Convert with int() or float().

          ⚠️ Exam Tip: Typical command-line program trap.

          Revision notes

          A module is a Python file with reusable code. You will learn how to import modules and use the standard-library modules math, os, random, statistics, sys and collections.

          High-Yield Quick Revision Points

          1. Module = .py file; import, import as, from ... import
          2. math: sqrt, ceil, floor, factorial, gcd, pi (radians for trig)
          3. os: getcwd, listdir, makedirs, path.join, exists, remove
          4. random: randint (both ends), randrange (stop excluded), choice, sample, shuffle
          5. statistics: mean, median, mode, pstdev vs stdev
          6. sys: argv (strings), exit, path, platform, getsizeof
          7. collections: Counter, defaultdict, deque, namedtuple

          Practice questions

          Question 1 · MCQ (Interview / semester)

          math.ceil(4.1) returns:

          Question 2 · MCQ (Interview / semester)

          Which function creates nested folders in one call?

          Question 3 · MCQ (Interview / semester)

          random.randint(1, 3) can return:

          Question 4 · MCQ (Interview / semester)

          statistics.median([1, 3, 2, 4]) is:

          Question 5 · MCQ (Interview / semester)

          sys.argv[0] holds:

          Question 6 · MCQ (Interview / semester)

          Which collections type counts items?

          Question 7 · MCQ (Interview / semester)

          Which statement imports only sqrt from math?