Python Modules (Random, Math & Statistical Functions) – Class 11 CS Notes
Learn Random, Math and Statistical Functions in Python with syntax, examples, outputs and important notes for Class 11 Computer Science students.
Introduction to Python Modules
A module in Python is a file that contains functions, variables, and statements that can be used in another Python program. A module is saved as a Python file with the extension .py.
Modules help in:
- Reusing code
- Reducing program size
- Avoid repetition of code
- Organizing programs properly
Built-in Modules in Python
Python provides many built-in modules in its standard library that help programmers perform different tasks easily.
Some commonly used built-in modules are:
- math
- random
- statistics
Importing Modules in Python
Modules can be imported using the import statement or the from statement.
Syntax
import module_name
Example
import math
print(math.sqrt(25))
Output
5.0
Importing multiple modules together in Python
Syntax
import modulename1, modulename2
Example
import math, random
Math Module in Python
The math module contains various mathematical functions and constants.
- Most functions in this module return values in float form.
- It is useful for performing mathematical calculations like square root, power, trigonometric operations, rounding, etc.
| Function / Constant | Description | Example |
| pi | Returns the value of π | import math print(math.pi) |
| e | Returns Euler’s number | import math print(math.e) |
| sqrt(x) | Returns square root of x | import math print(math.sqrt(49)) |
| ceil(x) | Rounds a number upward | import math print(math.ceil(4.2)) |
| floor(x) | Rounds a number downward | import math print(math.floor(4.9)) |
| pow(x,y) | Returns x raised to power y | import math print(math.pow(2,3)) |
| fabs(x) | Returns absolute value | import math print(math.fabs(-8)) |
| sin(x) | Returns sine of x | import math print(math.sin(0)) |
| cos(x) | Returns cosine of x | import math print(math.cos(0)) |
| tan(x) | Returns tangent of x | import math print(math.tan(0)) |
Random Module in Python
The random module is used to generate random numbers.
| Function | Description | Example |
| random() | Returns a random float between 0 and 1 | import random print(random.random()) |
| randint(a,b) | Returns a random integer between a and b | import random print(random.randint(1,10)) |
| randrange() | Returns a random number from a range | import random print(random.randrange(1,20,2)) |
Statistics Module in Python
The statistics module is used for statistical calculations.
| Function | Description | Example |
| mean() | Returns average value | import statistics data = [10,20,30,40] print(statistics.mean(data)) |
| median() | Returns middle value | import statistics data = [10,20,30,40] print(statistics.median(data)) |
| mode() | Returns most repeated value | import statistics data = [2,3,4,2,5] print(statistics.mode(data)) |