AmbifulWorksheets
Cheat sheet
CBSE · Class 11 · Computer Science

Python Modules: math, random and statistics

Importing modules and using math (sqrt, ceil, floor, pow, fabs, pi), random (random, randint, randrange) and statistics (mean, median, mode).

Key ideas

Remember

math resultsmath.sqrt(25) = 5.0; math.pow(2, 3) = 8.0 but 2 ** 3 = 8; math.fabs(−7) = 7.0
ceil and floormath.ceil(4.1) = 5; math.floor(7.9) = 7; math.floor(−2.5) = −3
Constantsmath.pi = 3.141592653589793; math.e = 2.718281828459045
random rangesrandint(1, 6): 1 to 6; randrange(0, 10, 2): 0, 2, 4, 6, 8; random(): 0 ≤ x < 1
How many valuesrandint(a, b) can give b − a + 1 different values
statisticsdata [4, 8, 8, 5]: mean 6.25, median 6.5, mode 8
Buses neededmath.ceil(students / seats): 130 students, 40 seats → 4 buses

Watch out

Worked example

What does this program print? Give the three lines (a) to (c).
import statistics as st
data = [29, 5, 21, 20, 20]
print(st.mean(data))
print(st.median(data))
print(st.mode(data))

Working: sum 95 ÷ 5; sorted: 5, 20, 20, 21, 29; mean of whole numbers prints without .0 only when it is exact, and the median of an even count is a float

Answer: (a) 19; (b) 20; (c) 20