COMPUTER SCIENCE
CLASS XI
01 Introduction to Python modules
What is a module?
•A Python file containing a set of functions and variables to be
used in an application.
•The variables can be of any type (lists, dictionaries etc.)
•Any text file with .py extension and containing Python code is
basically a module.
•To call a built-in Module and use the function of that module
write:
import moduleName #call a module
[Link]() #use module function
Benefits of modules in Python
Key benefits of creating and using a module in Python:
Structured Code
•Code is logically organized by being grouped into one Python file
which makes development easier and less error-prone.
•Code is easier to understand and use.
Reusability
Functionality defined in a single module can be easily reused by
other parts of the application. This eliminates the need to recreate
duplicate code.
List modules in Python to discuss:
math module
pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan
statistics module
mean, median, mode
How to use a module
import math
print([Link](25))
import statistics
print([Link]([1, 3, 3, 3, 5, 7, 7, 9])) 3
import statistics as st
print([Link]([1, 3, 3, 3, 5, 7, 7, 9])) 3
math module
pi : Mathematical constant, the ratio of circumference of a
circle to it's diameter
Example
import math
print([Link]) 3.141592653589793
math module
e : Mathematical constant. It is called Euler's number .
Example
import math
print(math.e) 2.718281828459045
math module
sqrt(x) : returns the square root of a given number x.
Example
import math
print([Link](64)) 8
math module
ceil(x) : Returns the smallest integer greater than or equal to x.
Example
import math
print([Link](7.2)) 8
print([Link](7.7)) 8
print([Link](-7.2)) -7
print([Link](-7.9)) -7
math module
floor(x): Returns the largest integer less than or equal to x.
Example
import math
print([Link](7.2)) 7
print([Link](7.7)) 7
print([Link](-7.2)) -8
print([Link](-7.9)) -8
math module
pow(x, y) : Returns x raised to the power y.
Example
import math
print([Link](7,2)) 49.0
math module
fabs(x) : Returns the absolute value of x. It removes the negative
sign of the value if it has any.
Example
import math
print([Link](7)) 7
print([Link](-7)) 7
statistics module
mean() : calculates the mean (average) of the given data
set.
Example
import statistics
print([Link]([1, 3, 5, 7, 9, 11, 13])) 7
print([Link]([-11, 5.5, -3.4, 7.1, -9, 22]))
1.8666666666666667
statistics module
median() : Calculate the median (middle value) of the given
data.
Example
import statistics
print([Link]([1, 3, 5, 7, 9, 11, 13])) 7
print([Link]([1, 3, 5, 7, 9, 11])) 6.0
statistics module
mode() : Calculate the mode (central tendency) of the given
data.
Example
import statistics
print([Link] ([1, 3, 3, 3, 5, 7, 7, 9])) 3
print([Link](['red', 'green', 'blue', 'red'])) red