VM-LEARNING /class.xi ·track.cs ·ch-2-14 session: 2026_27
$cd ..

~/Introduction to Python Modules

root@vm-learning ~ $ open ch-2-14
UNIT 2 ▪ CHAPTER 14
20
Introduction to Python Modules
import · from · math · random · statistics
A module is simply a Python file (ending in .py) that contains variables, functions, and classes which can be re-used by other programs. Python ships with a standard library of around 200 ready-to-use modules — collectively called the "batteries included" philosophy. Need a square root? Import math. Need a random number? Import random. Need the average of a list? Import statistics. This chapter introduces the three modules named in the CBSE Class XI syllabus and the different ways to pull them into your program.
Why modules matter:
  • Re-use — no need to re-invent sqrt, sin, or a dice roller.
  • Organisation — related functions live together (math, random, datetime…).
  • Namespaces — a function named mean inside statistics does not clash with a variable you call mean.
  • Community power — beyond the standard library, thousands of third-party modules (NumPy, Pandas, Flask…) can be installed with pip install.
Learning Outcome 1: Import Python modules using the import and from forms.

20.1 Four Ways to Import

The four import forms: 1. import module import math Access as math.sqrt(9) — prefix every name with the module. Safest — no risk of name clashes. Recommended for most code. 2. from module import name(s) from math import sqrt, pi Access as sqrt(9) — no prefix needed. Shorter, but can collide with your own names. 3. from module import * from math import * Brings in everythingsqrt, sin, pi… all become top-level names. ⚠ Discouraged — pollutes your namespace, hides shadowed names. 4. import module as alias import statistics as st Access as st.mean(L) — give the module a nickname. Standard in data science: import numpy as np.

20.1.1 Which form should I use?

Use caseRecommended form
Most code, most of the timeimport module
You need only one or two specific namesfrom module import name
The module name is long or conventionalimport module as alias (e.g. np, pd, plt)
Exam-scripting "just get it to work"from module import * — works, but never use in real projects

20.1.2 Exploring a module

Two built-ins let you peek inside any module at any time:

import math
print(dir(math))          # full list of names math exports
help(math.sqrt)          # documentation for sqrt
Learning Outcome 2: Use constants and functions of the math module.

20.2 The math Module

The math module provides mathematical constants and real-number functions (integers & floats). For complex numbers, use the sister module cmath.

20.2.1 Constants

ConstantMeaningApproximate value
math.piπ — ratio of a circle's circumference to its diameter3.141592653589793
math.ee — base of natural logarithm2.718281828459045
math.infpositive infinity
math.nanNot-a-Numberundefined

20.2.2 Functions listed in the CBSE syllabus

FunctionEffectExampleResult
sqrt(x)Square root of x. Returns a float. x must be ≥ 0.math.sqrt(16)4.0
ceil(x)Smallest integer ≥ x (rounded up).math.ceil(3.2)4
floor(x)Largest integer ≤ x (rounded down).math.floor(3.8)3
pow(x, y)x raised to y. Returns a float.math.pow(2, 10)1024.0
fabs(x)Absolute value — always a float.math.fabs(-7)7.0
sin(x)Sine of x. x must be in radians.math.sin(math.pi/2)1.0
cos(x)Cosine (x in radians).math.cos(0)1.0
tan(x)Tangent (x in radians).math.tan(math.pi/4)0.9999… (≈ 1)
Degrees vs radians. All trig functions expect the angle in radians. Convert using math.radians(deg) or multiply by math.pi/180:
print(math.sin(math.radians(30)))     # 0.5
math.pow(x, y) always returns a float: math.pow(2, 10)1024.0. The built-in pow(x, y) (or **) preserves integer type: pow(2, 10)1024. Also, math.fabs always gives a float, while the built-in abs keeps the input type.
Worked example — area and circumference of a circle:
import math

r = float(input("Radius (cm): "))
area = math.pi * math.pow(r, 2)       # π r²
circ = 2 * math.pi * r
print(f"Area          : {area:.2f} cm²")
print(f"Circumference : {circ:.2f} cm")
For r = 7:
Area          : 153.94 cm²
Circumference : 43.98 cm
Worked example — roots of a quadratic ax² + bx + c = 0:
import math

a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))

d = b*b - 4*a*c                         # discriminant

if d < 0:
    print("No real roots")
else:
    sqrt_d = math.sqrt(d)
    x1 = (-b + sqrt_d) / (2*a)
    x2 = (-b - sqrt_d) / (2*a)
    print("Roots:", x1, ",", x2)
Learning Outcome 3: Use the random module to generate random numbers.

20.3 The random Module

The random module generates pseudo-random numbers — sequences that look random but are produced by a deterministic algorithm seeded from the system clock. The three functions named in the syllabus cover 99% of class-room needs.

FunctionEffectTypical range
random()A random float in the half-open interval [0.0, 1.0)0.0 ≤ x < 1.0
randint(a, b)A random integer from a to bboth inclusivea ≤ n ≤ b
randrange(start, stop, step)A random integer from a range(...)stop excluded; same rules as range()start ≤ n < stop
The big difference between the two integer functions:
  • randint(1, 6) → any value from 1, 2, 3, 4, 5 or 6 — upper bound included.
  • randrange(1, 6) → any value from 1, 2, 3, 4 or 5 — upper bound excluded.
import random

print(random.random())              # e.g., 0.8723456...
print(random.randint(1, 6))          # a dice roll — 1 to 6
print(random.randrange(0, 100, 5))   # one of 0, 5, 10, ..., 95

20.3.1 A few useful bonus functions

Not in the syllabus but handy:

random.choice(["rock", "paper", "scissors"])   # pick one at random
random.shuffle(my_list)                           # shuffle in place
random.sample(range(1, 50), 6)                      # 6 unique numbers — lottery draw
random.uniform(1.0, 10.0)                           # random float in [1.0, 10.0]
random.seed(42)                                    # make the "random" sequence reproducible
Worked example — Dice-roll simulator:
import random

for i in range(5):
    roll = random.randint(1, 6)
    print(f"Roll {i+1}: 🎲 {roll}")
Sample output:
Roll 1: 🎲 4
Roll 2: 🎲 2
Roll 3: 🎲 6
Roll 4: 🎲 1
Roll 5: 🎲 5
Worked example — generate a 6-digit OTP:
import random

otp = random.randint(100000, 999999)
print(f"Your OTP is {otp}")
Learning Outcome 4: Use the statistics module to compute mean, median and mode.

20.4 The statistics Module

The statistics module provides basic descriptive-statistics functions. It works on any iterable of numbers (list, tuple, set).

FunctionEffectExample (data = [85, 72, 91, 72, 77])
mean(data)Arithmetic mean (average) = Σ / n79.4
median(data)Middle value when sorted. For an even-length list, the average of the two middles.77
mode(data)The most frequently occurring value. Works on strings too.72 (appears twice)
import statistics

data = [85, 72, 91, 72, 77]

print("Mean   =", statistics.mean(data))     # 79.4
print("Median =", statistics.median(data))   # 77
print("Mode   =", statistics.mode(data))     # 72
Bonus — other useful stat functions you may meet:
statistics.stdev(data)          # sample standard deviation
statistics.variance(data)       # sample variance
statistics.pstdev(data)         # population standard deviation
statistics.median_low(data)     # lower of the two middles (even n)
statistics.median_high(data)    # upper of the two middles
Learning Outcome 5: Combine modules to write useful mini-programs.

20.5 Putting It Together — Worked Programs

20.5.1 Marks-statistics report

import statistics

marks = [85, 72, 91, 72, 77, 68, 95, 82]

print(f"Students      : {len(marks)}")
print(f"Highest       : {max(marks)}")
print(f"Lowest        : {min(marks)}")
print(f"Mean          : {statistics.mean(marks):.2f}")
print(f"Median        : {statistics.median(marks)}")
print(f"Mode          : {statistics.mode(marks)}")
print(f"Std deviation : {statistics.stdev(marks):.2f}")

20.5.2 Guess-the-number game

import random

secret = random.randint(1, 100)
tries  = 0

while True:
    guess = int(input("Your guess (1-100): "))
    tries += 1
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
    else:
        print(f"Got it in {tries} tries!")
        break

20.5.3 Hypotenuse of a right triangle

from math import sqrt            # pull only what we need

a = float(input("Side a: "))
b = float(input("Side b: "))
c = sqrt(a*a + b*b)
print(f"Hypotenuse = {c:.2f}")
For a = 3, b = 4: Hypotenuse = 5.00

20.5.4 Roll two dice 10 000 times — frequency of each total

import random

freq = {}
for _ in range(10000):
    total = random.randint(1,6) + random.randint(1,6)
    freq[total] = freq.get(total, 0) + 1

for total in sorted(freq):
    print(f"{total}: {freq[total]}")
Typical output:  7 is the most common total (~1666 times); 2 and 12 are the rarest (~278 each).

20.6 Modules — One-page Summary

ModuleWhat it providesCBSE items
mathMathematical constants + real-number functionsconstants pi, e; sqrt, ceil, floor, pow, fabs, sin, cos, tan
randomPseudo-random number generationrandom(), randint(a, b), randrange(start, stop, step)
statisticsDescriptive statistics on numeric datamean(), median(), mode()
Other standard-library modules you'll meet in Class XII and beyond: datetime (dates & times), os / sys (operating system), csv (CSV files), json (JSON), pickle (binary files), re (regex), collections (Counter, deque), pickle. Third-party favourites installed with pip: numpy, pandas, matplotlib, requests, flask, django.

📌 Quick Revision — Chapter 20 at a Glance

  • Module = a Python file of re-usable variables, functions, classes. The standard library ships ~200 of them.
  • Four import forms:
    • import module — access as module.name. Safest, preferred.
    • from module import name — access as just name. Shorter, may clash.
    • from module import * — brings in everything. Avoid.
    • import module as alias — rename on import (numpy as np).
  • dir(module) lists its names; help(module.name) reads its docs.
  • math module:
    • Constants: math.pi, math.e.
    • Functions: sqrt(x), ceil(x), floor(x), pow(x, y) (always float), fabs(x) (always float), sin(x), cos(x), tan(x) — trig in radians. Use radians(deg) to convert.
  • random module:
    • random() — float in [0.0, 1.0).
    • randint(a, b) — int with both bounds included.
    • randrange(start, stop, step) — same as range(), excluding stop.
    • Bonus: choice, shuffle, sample, uniform, seed.
  • statistics module: mean(), median(), mode(). Also stdev() / variance().
  • math.pow vs built-in pow: math.pow always returns float; pow (or **) preserves int.
  • math.fabs vs built-in abs: math.fabs always returns float; abs preserves input type.
  • Classic programs combining modules: circle area, quadratic roots, hypotenuse, OTP generator, dice simulator, marks-statistics report, guess-the-number game.
Unit 3
🛡️
Society, Law
and Ethics
Digital citizenship · Cyber safety · IPR · IT Act
Ch 21 • Digital Footprints · Netiquette · Cyber Crime
IPR · Malware · E-waste · IT Act · Gender & Disability Issues
🧠Practice Quiz — test yourself on this chapter