Worksheets › Class 11 › Python Modules: math, random and statistics › Cheat sheet
Class 11 Python Modules: math, random and statistics: cheat sheet
CBSE Computer Science. Importing modules and using math (sqrt, ceil, floor, pow, fabs, pi), random (random, randint, randrange) and statistics (mean, median, mode).
Key ideas
- import math loads the whole module, so its functions are called as math.sqrt(x); from math import sqrt lets you write sqrt(x).
- math.sqrt(), math.pow() and math.fabs() always give floats; math.ceil() and math.floor() give ints.
- ceil() rounds up to the next whole number and floor() rounds down, so for a negative number floor() moves away from zero.
- random.random() gives a float from 0 up to but not including 1; randint(a, b) includes both a and b; randrange(a, b, c) stops before b.
- statistics.mean() adds and divides; median() is the middle of the sorted data (the mean of the two middle values for an even count); mode() is the most frequent value.
- mean() of whole numbers prints as an int when it is exact (19) and as a float when not (19.4); a median of an even count is a float.
Remember
| math results | math.sqrt(25) = 5.0; math.pow(2, 3) = 8.0 but 2 ** 3 = 8; math.fabs(−7) = 7.0 |
| ceil and floor | math.ceil(4.1) = 5; math.floor(7.9) = 7; math.floor(−2.5) = −3 |
| Constants | math.pi = 3.141592653589793; math.e = 2.718281828459045 |
| random ranges | randint(1, 6): 1 to 6; randrange(0, 10, 2): 0, 2, 4, 6, 8; random(): 0 ≤ x < 1 |
| How many values | randint(a, b) can give b − a + 1 different values |
| statistics | data [4, 8, 8, 5]: mean 6.25, median 6.5, mode 8 |
| Buses needed | math.ceil(students / seats): 130 students, 40 seats → 4 buses |
Watch out
- Writing sqrt(16) after import math: it must be math.sqrt(16).
- Expecting randint(1, 6) to stop at 5: unlike range(), it includes both ends.
- Writing 8 for math.pow(2, 3): it gives 8.0.
- Taking the middle of the unsorted data as the median.
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
Practise Python Modules: math, random and statistics
Revise with this page, then practise: every Python Modules: math, random and statistics sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.