Do you build your own calculator every time you need a square root? Of course not! Python programmers don't either. Python comes with hundreds of ready-made tools packed into modules โ for maths, random numbers, statistics, dates, and much more. You just import a module and use its functions. This chapter explains what a module is, the different ways to import one, the main functions of the math, random and statistics modules, how to predict the possible outputs of a program that uses random numbers, and how to create a module of your own.
Focus especially on import vs from ... import, ceil() vs floor() (with negative numbers!), randint() vs randrange(), mean() / median() / mode(), and the "possible outputs" questions on the random module โ revise these carefully.
13.1 ๐ Introduction
A module is a Python file (.py) that contains ready-made definitions โ functions, variables (constants) and classes โ which can be reused in other programs by importing it.
import math
print(math.sqrt(81)) # 9.0
print(math.pi) # 3.141592653589793
Reusability
Write code once in a module and use it in many programs
No copy-pasteModularity
A big program is divided into smaller files that are easy to manage
Organised codeNamespace
Names inside a module don't clash with names in your program
math.pow vs powSaves Time
Tested, ready-made functions โ no need to write them yourself
Fewer bugsTypes of modules:
| Type | Meaning | Examples |
|---|---|---|
| Built-in / Standard Library modules | Come with Python; just import and use | math, random, statistics, datetime |
| User-defined modules | .py files written by you |
mytools.py |
| Third-party modules / packages | Downloaded and installed using pip |
numpy, pandas, matplotlib |
Analogy: Python's standard library is like a school library ๐. Each module is a book on one subject (maths, statisticsโฆ). You don't copy the whole book into your notebook โ you just borrow (import) it and read the page (function) you need!
13.2 ๐ฅ Importing Modules
There are three common ways to import a module.
13.2.1 import <module> โ Import the Whole Module
import math
print(math.sqrt(16)) # 4.0
print(math.floor(7.8)) # 7
You must write the module name, a dot, then the function name (math.sqrt). This is called dot notation.
You can also give the module a short alias using as:
import statistics as st
print(st.mean([10, 20, 30])) # 20
13.2.2 from <module> import <name> โ Import Selected Names
from math import sqrt, pi
print(sqrt(25)) # 5.0 โ no "math." needed
print(pi) # 3.141592653589793
# print(floor(2.5)) # โ NameError โ floor was not imported
13.2.3 from <module> import * โ Import Everything
from math import *
print(ceil(4.1), floor(4.9)) # 5 4
Comparing the three ways:
| Style | How to call a function | Imports | Risk of name clash |
|---|---|---|---|
import math |
math.sqrt(9) |
The whole module | โ None |
from math import sqrt |
sqrt(9) |
Only sqrt |
โ ๏ธ Low |
from math import * |
sqrt(9) |
All the names | โ ๏ธ High โ may overwrite your own names |
After import math, writing sqrt(9) gives NameError: name 'sqrt' is not defined โ you must write math.sqrt(9). After from math import sqrt, writing math.sqrt(9) gives NameError: name 'math' is not defined. Match the call to the import style!
"Differentiate between import math and from math import sqrt." โ 2-mark question!
Answer: import math imports the whole module, and its functions must be called using the module name with dot notation, e.g. math.sqrt(9). from math import sqrt imports only sqrt into the program, so it is called directly as sqrt(9), without the module name.
dir(math) lists all the names inside the math module, and help(math.sqrt) shows what sqrt does. Try them in the Python shell!
13.3 ๐ The math Module
The math module provides mathematical functions and constants. Remember to import math first.
13.3.1 Constants
| Constant | Value | Meaning |
|---|---|---|
math.pi |
3.141592653589793 |
ฯ โ ratio of a circle's circumference to its diameter |
math.e |
2.718281828459045 |
Euler's number โ base of natural logarithms |
13.3.2 Functions
| Function | Description | Example | Result |
|---|---|---|---|
math.sqrt(x) |
Square root of x (x โฅ 0); always a float | math.sqrt(49) |
7.0 |
math.ceil(x) |
Smallest integer โฅ x (rounds UP) | math.ceil(4.2) |
5 |
math.floor(x) |
Largest integer โค x (rounds DOWN) | math.floor(4.8) |
4 |
math.pow(x, y) |
x raised to the power y; always a float | math.pow(2, 5) |
32.0 |
math.fabs(x) |
Absolute value of x; always a float | math.fabs(-7) |
7.0 |
math.sin(x) |
Sine of x (x in radians) | math.sin(0) |
0.0 |
math.cos(x) |
Cosine of x (x in radians) | math.cos(0) |
1.0 |
math.tan(x) |
Tangent of x (x in radians) | math.tan(0) |
0.0 |
import math
print(math.ceil(-2.5)) # -2 (โ2 is the smallest integer โฅ โ2.5)
print(math.floor(-2.5)) # -3 (โ3 is the largest integer โค โ2.5)
print(math.ceil(7)) # 7 (already an integer)
print(math.pow(4, 0.5)) # 2.0
print(2 ** 5, math.pow(2, 5)) # 32 32.0
print(abs(-7), math.fabs(-7)) # 7 7.0
ceil() and floor() on a number line:
floor(-2.5) = -3 ceil(-2.5) = -2 floor(4.2) = 4 ceil(4.2) = 5
โ โ โ โ
โโโโโโโผโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโ โฆ โโโโโโโโโโโโผโโโโโโโโโโโโโโโโผโโโโโโ
-3 -2.5 -2 4 4.2 5
Look up at your room's ceiling โฌ๏ธ โ ceil() always moves up the number line. Look down at the floor โฌ๏ธ โ floor() always moves down. For negative numbers, "down" means MORE negative: floor(-2.5) is โ3!
Trigonometric functions use RADIANS, not degrees. Convert degrees with math.radians():
import math
angle = math.radians(90) # 90ยฐ โ 1.5707963267948966 radians
print(math.sin(angle)) # 1.0
print(round(math.cos(math.radians(60)), 2)) # 0.5
math.sin(90) does NOT give 1.0 โ it gives the sine of 90 radians (0.8939966636005579). Always convert degrees to radians first. Also, math.sqrt(-4) gives ValueError: math domain error.
"What is the difference between math.ceil() and math.floor()? Give the output of math.ceil(-3.7) and math.floor(-3.7)." โ 2-mark question!
Answer: ceil(x) returns the smallest integer greater than or equal to x; floor(x) returns the largest integer less than or equal to x. math.ceil(-3.7) โ โ3 and math.floor(-3.7) โ โ4.
13.4 ๐ฒ The random Module
The random module generates random (unpredictable) numbers โ useful for games, dice, OTPs, quizzes and simulations. Remember to import random first.
| Function | Returns | Range | Example |
|---|---|---|---|
random.random() |
A random float | 0.0 โค n < 1.0 (1.0 never comes) | 0.5488135039273248 |
random.randint(a, b) |
A random integer | a โค n โค b (BOTH ends included) | random.randint(1, 6) โ 1 to 6 |
random.randrange(stop) |
A random integer | 0 โค n < stop | random.randrange(5) โ 0 to 4 |
random.randrange(start, stop) |
A random integer | start โค n < stop | random.randrange(1, 6) โ 1 to 5 |
random.randrange(start, stop, step) |
A random integer from range(start, stop, step) |
stop excluded | random.randrange(0, 20, 5) โ 0, 5, 10 or 15 |
import random
print(random.randint(1, 6)) # a dice roll: 1, 2, 3, 4, 5 or 6
print(random.randrange(10, 100, 10)) # 10, 20, โฆ or 90 (never 100)
print(random.random()) # e.g. 0.7319939418114051
Useful tricks with random.random():
import random
# Random integer from 10 to 20 (both included) using random():
n = int(random.random() * 11) + 10
# random() * 11 โ 0.0 to 10.999โฆ โ int() โ 0 to 10 โ + 10 โ 10 to 20
print(n)
randint() vs randrange() โ The Critical Comparison:
| Feature | randint(a, b) |
randrange(start, stop, step) |
|---|---|---|
| Upper limit | โ Included | โ Excluded |
| Step allowed? | No | Yes |
(1, 10) gives |
1 to 10 | 1 to 9 |
| Arguments | Exactly 2 | 1, 2 or 3 |
randINT โ INcludes both ends. randRANGE โ behaves exactly like range() โ the stop value is never included!
13.4.1 Predicting Possible Outputs ๐ฎ
Because random numbers are unpredictable, exams ask: "Which of the given outputs are POSSIBLE?" The method:
- Find the smallest and largest value each random call can produce.
- Work out what the program prints for those limits.
- Check each option against these limits.
Example:
import random
AR = [20, 30, 40, 50, 60, 70]
FROM = random.randint(1, 3)
TO = random.randint(2, 4)
for K in range(FROM, TO + 1):
print(AR[K], end="#")
Which outputs are possible? (i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#
Indices : 0 1 2 3 4 5
AR : 20 30 40 50 60 70
FROM can be 1, 2 or 3 TO can be 2, 3 or 4
K runs from FROM to TO โ the printed indices are CONSECUTIVE, between 1 and 4
So only values from AR[1] to AR[4] (30, 40, 50, 60) can be printed, in order.
(If FROM = 3 and TO = 2, the range is empty and nothing is printed.)
| Option | Possible? | Reason |
|---|---|---|
(i) 10#40#70# |
โ No | 10 is not in AR, and 70 (index 5) can never be printed |
(ii) 30#40#50# |
โ Yes | FROM = 1, TO = 3 |
(iii) 50#60#70# |
โ No | 70 needs index 5, but TO is at most 4 |
(iv) 40#50#70# |
โ No | Values must be consecutive, and 70 can't appear |
Maximum values: FROM = 3, TO = 4. Minimum values: FROM = 1, TO = 2.
"Possible output" questions on the random module usually carry 2 marks. Always write the index positions above the list and state the minimum and maximum value of each random variable. Remember: randint() includes the upper limit, randrange() excludes it.
13.5 ๐ The statistics Module
The statistics module calculates measures of central tendency of numeric data. Remember to import statistics first.
| Function | Meaning | Example | Result |
|---|---|---|---|
statistics.mean(data) |
Average โ sum รท count | statistics.mean([2, 4, 6, 8]) |
5 |
statistics.median(data) |
Middle value of the sorted data | statistics.median([7, 1, 5]) |
5 |
statistics.mode(data) |
Most frequent value | statistics.mode([3, 1, 3, 2, 3]) |
3 |
import statistics as st
marks = [72, 85, 90, 85, 60, 78]
print(st.mean(marks)) # 78.33333333333333
print(st.median(marks)) # 81.5
print(st.mode(marks)) # 85
print(st.mode(["red", "blue", "red"])) # red (mode works on strings too!)
How the median is calculated:
Odd count โ [7, 1, 5] sorted โ [1, 5, 7] middle = 5
Even count โ [72, 85, 90, 85, 60, 78]
sorted โ [60, 72, 78, 85, 85, 90]
two middle values โ 78 and 85 โ median = (78 + 85) / 2 = 81.5
mean()
Add all the values and divide by how many there are
Averagemedian()
Sort the data; take the middle value (average of the two middle values for an even count)
Middlemode()
The value that occurs the MOST number of times
Most commonThe median is the middle of the SORTED data โ not the middle of the list as given! For [7, 1, 5], the median is 5, not 1. Also, statistics.mean([]) gives a StatisticsError (there is no average of nothing).
Mean = means "average" ยท Median = medium, the middle ยท Mode = most often.
13.6 ๐ ๏ธ Creating Your Own Module
Any .py file you write can be used as a module!
Code Example: geometry.py
# geometry.py โ a user-defined module
PI = 3.14159
def circle_area(r):
return PI * r * r
def rect_area(l, b):
return l * b
Code Example: main.py
# main.py โ saved in the SAME folder as geometry.py
import geometry
print(geometry.circle_area(7)) # 153.93791
print(geometry.rect_area(4, 5)) # 20
You'll learn how to write your own functions (def) in detail in Class 12 โ Working with Functions. For now, just remember that a module is simply a .py file whose functions can be imported.
13.7 ๐ป Important Programs Using Modules
Code Example: quadratic_roots.py
# Roots of axยฒ + bx + c = 0 using math.sqrt()
import math
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
d = b * b - 4 * a * c
if d > 0:
r1 = (-b + math.sqrt(d)) / (2 * a)
r2 = (-b - math.sqrt(d)) / (2 * a)
print("Real and different roots:", r1, r2)
elif d == 0:
print("Real and equal roots:", -b / (2 * a))
else:
print("Roots are imaginary")
# Input a=1, b=-5, c=6 โ Real and different roots: 3.0 2.0
Code Example: dice_game.py
# Roll two dice 5 times and count how often they show doubles
import random
doubles = 0
for turn in range(1, 6):
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
print("Turn", turn, ":", d1, d2)
if d1 == d2:
doubles += 1
print("Doubles:", doubles)
Code Example: otp_generator.py
# Generate a random 4-digit OTP
import random
otp = random.randint(1000, 9999)
print("Your OTP is", otp)
Code Example: marks_statistics.py
# Mean, median and mode of marks entered by the user
import statistics
marks = eval(input("Enter a list of marks: "))
print("Mean :", round(statistics.mean(marks), 2))
print("Median:", statistics.median(marks))
print("Mode :", statistics.mode(marks))
# Input [45, 67, 89, 67, 90, 55] โ
# Mean : 68.83
# Median: 67.0
# Mode : 67
Code Example: circle_calc.py
# Area and circumference of a circle using math.pi
from math import pi
r = float(input("Enter radius: "))
print("Area =", round(pi * r ** 2, 2))
print("Circumference =", round(2 * pi * r, 2))
# Input 7 โ Area = 153.94
# Circumference = 43.98
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
โ Using sqrt(9) after import math |
The name needs the module prefix | โ
math.sqrt(9), or use from math import sqrt |
โ math.sqrt(16) gives 4 |
sqrt() returns a float | โ
It gives 4.0 |
โ math.floor(-2.5) gives -2 |
floor goes DOWN the number line | โ
It gives -3 |
โ math.pow(2, 3) gives 8 |
pow() returns a float | โ
It gives 8.0 (but 2 ** 3 gives 8) |
โ math.sin(90) gives 1.0 |
Angles must be in radians | โ
math.sin(math.radians(90)) gives 1.0 |
โ random.randint(1, 10) never gives 10 |
randint includes both ends | โ It can give 1 to 10 |
โ random.randrange(1, 10) can give 10 |
randrange excludes stop | โ It gives 1 to 9 |
โ random.random() can return 1.0 |
Upper limit is excluded | โ 0.0 โค value < 1.0 |
| โ The median is the middle element of the list as given | The data must be sorted first | โ Sort, then take the middle |
๐ Quick Revision
Importing:
import mathโmath.sqrt(9)import statistics as stโst.mean(L)from math import sqrt, piโsqrt(9)from math import *โ everything (risk of name clashes)
math module: pi, e, sqrt() (float), ceil() (up), floor() (down), pow() (float), fabs() (float), sin() / cos() / tan() (radians)
random module:
| Function | Range |
|---|---|
random() |
0.0 โค n < 1.0 |
randint(a, b) |
a โค n โค b |
randrange(a, b, s) |
a โค n < b, in steps of s |
statistics module: mean() โ average ยท median() โ middle of sorted data ยท mode() โ most frequent
๐ฏ Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the output of print(math.ceil(3.01), math.floor(3.99))?
โ 4 3
b) Which module must be imported to use mode()?
โ statistics
c) What is the range of values returned by random.randint(5, 10)?
โ Integers from 5 to 10 (both included)
d) What will math.fabs(-12) return?
โ 12.0
e) Name the constant in the math module that stores the value of ฯ.
โ math.pi
Q2: Output Based [2 marks]
Q: Write the output of the following code:
import math
import statistics as st
print(math.sqrt(64) + math.pow(2, 3))
print(math.floor(-4.2), math.ceil(-4.2))
print(st.median([9, 3, 7, 1]), st.mode([4, 2, 4, 6, 2, 4]))
Answer:
16.0
-5 -4
5.0 4
Q3: Possible Output [2 marks]
Q: What are the possible outputs of the following code? Also write the maximum and minimum values that N can take.
import random
COLOURS = ["RED", "GREEN", "BLUE", "PINK", "GOLD"]
N = random.randrange(1, 4)
for i in range(N):
print(COLOURS[i], end="-")
(i) RED- (ii) RED-GREEN-BLUE-PINK- (iii) GREEN-BLUE- (iv) RED-GREEN-BLUE-
Answer:
N can be 1, 2 or 3 โ Minimum = 1, Maximum = 3. The loop always starts from index 0 (RED).
- (i)
RED-โ possible (N = 1) - (ii) โ not possible โ needs N = 4, but
randrange(1, 4)never gives 4 - (iii) โ not possible โ the output must start with
RED - (iv)
RED-GREEN-BLUE-โ possible (N = 3)
Q4: Short Answer [2 marks]
Q: Differentiate between random.randint() and random.randrange() with an example.
randint(a, b) returns a random integer between a and b, including both a and b; e.g. randint(1, 5) can return 1 to 5.
randrange(start, stop, step) returns a random integer from range(start, stop, step), so the stop value is excluded; e.g. randrange(1, 5) can return 1 to 4. randrange() also allows a step value.
Q5: Program [3 marks]
Q: Write a program that generates 10 random integers between 1 and 100, stores them in a list, and prints the list along with its mean, median and the largest number.
import random
import statistics
nums = []
for i in range(10):
nums.append(random.randint(1, 100))
print("Numbers:", nums)
print("Mean:", statistics.mean(nums))
print("Median:", statistics.median(nums))
print("Largest:", max(nums))
โ๏ธ Practice Problems
-
What is a module? Write any three advantages of using modules.
-
Write the output of: (a)
math.ceil(-0.5)(b)math.floor(0.5)(c)math.pow(3, 2)(d)math.sqrt(math.pow(3, 2) + math.pow(4, 2)) -
Write a program to input the angle in degrees and print its sine, cosine and tangent, rounded to 3 decimal places.
-
Write a program to simulate tossing a coin 20 times and count the number of heads and tails.
-
Write a program to input 5 numbers into a list and print their mean, median and mode using the
statisticsmodule. -
What are the minimum and maximum values that
xcan take?x = random.randrange(5, 50, 5) + 1 -
What are the possible outputs of the following code?
import random L = [10, 20, 30, 40, 50] start = random.randint(0, 2) for i in range(start, start + 2): print(L[i], end=" ")(i)
10 20(ii)30 40(iii)40 50(iv)20 30 -
Write a program to generate a random 6-character password made up of capital letters only (hint:
chr(random.randint(65, 90))). -
Differentiate between
import mathandfrom math import *. Which one is safer and why? -
Write a program that asks the user to guess a random number between 1 and 20, and tells them whether each guess is too high, too low or correct, until they guess it.