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
meaninsidestatisticsdoes not clash with a variable you callmean. - 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:
20.1.1 Which form should I use?
| Use case | Recommended form |
|---|---|
| Most code, most of the time | import module |
| You need only one or two specific names | from module import name |
| The module name is long or conventional | import 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
| Constant | Meaning | Approximate value |
|---|---|---|
math.pi | π — ratio of a circle's circumference to its diameter | 3.141592653589793 |
math.e | e — base of natural logarithm | 2.718281828459045 |
math.inf | positive infinity | ∞ |
math.nan | Not-a-Number | undefined |
20.2.2 Functions listed in the CBSE syllabus
| Function | Effect | Example | Result |
|---|---|---|---|
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.
| Function | Effect | Typical 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 b — both inclusive | a ≤ 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).
| Function | Effect | Example (data = [85, 72, 91, 72, 77]) |
|---|---|---|
mean(data) | Arithmetic mean (average) = Σ / n | 79.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
| Module | What it provides | CBSE items |
|---|---|---|
math | Mathematical constants + real-number functions | constants pi, e; sqrt, ceil, floor, pow, fabs, sin, cos, tan |
random | Pseudo-random number generation | random(), randint(a, b), randrange(start, stop, step) |
statistics | Descriptive statistics on numeric data | mean(), 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 asmodule.name. Safest, preferred.from module import name— access as justname. 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.mathmodule:- 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. Useradians(deg)to convert.
- Constants:
randommodule:random()— float in [0.0, 1.0).randint(a, b)— int with both bounds included.randrange(start, stop, step)— same asrange(), excluding stop.- Bonus:
choice,shuffle,sample,uniform,seed.
statisticsmodule:mean(),median(),mode(). Alsostdev()/variance().math.powvs built-inpow:math.powalways returns float;pow(or**) preserves int.math.fabsvs built-inabs:math.fabsalways returns float;abspreserves 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
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
IPR · Malware · E-waste · IT Act · Gender & Disability Issues