|

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 / ConstantDescriptionExample
piReturns the value of πimport math print(math.pi)
eReturns Euler’s numberimport math print(math.e)
sqrt(x)Returns square root of ximport math print(math.sqrt(49))
ceil(x)Rounds a number upwardimport math print(math.ceil(4.2))
floor(x)Rounds a number downwardimport math print(math.floor(4.9))
pow(x,y)Returns x raised to power yimport math print(math.pow(2,3))
fabs(x)Returns absolute valueimport math print(math.fabs(-8))
sin(x)Returns sine of ximport math print(math.sin(0))
cos(x)Returns cosine of ximport math print(math.cos(0))
tan(x)Returns tangent of ximport math print(math.tan(0))

Random Module in Python

The random module is used to generate random numbers.

FunctionDescriptionExample
random()Returns a random float between 0 and 1import random print(random.random())
randint(a,b)Returns a random integer between a and bimport random print(random.randint(1,10))
randrange()Returns a random number from a rangeimport random print(random.randrange(1,20,2))

Statistics Module in Python

The statistics module is used for statistical calculations.

FunctionDescriptionExample
mean()Returns average valueimport statistics data = [10,20,30,40] print(statistics.mean(data))
median()Returns middle valueimport statistics data = [10,20,30,40] print(statistics.median(data))
mode()Returns most repeated valueimport statistics data = [2,3,4,2,5] print(statistics.mode(data))

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *