11 Notes Modules
11 Notes Modules
CBSE Syllabus
Introduction to Python modules: Importing module using 'import <module>' and using ‘from’
statement,
Importing
• math module (pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan);
• random module (random, randint, randrange),
• statistics module (mean, median, mode)
A module is a piece of Python code. A module allows you to logically organize your Python code. A
module is a file that contains Python statements and definitions. The modules in Python have the .py
extension.
Python itself is having a vast module library and packages with the default installation. To use any
package in your code, you must first make it accessible. You have to import it using the import
directive. For example,
import math
import random
import statistics
Notice that after using the above three import statements, you can access all built in functions into
your current Python program or at interactive mode.
P
o 1. Modules contain readymade codes called functions.
i 2. Functions are bunched in different modules.
n 3. All Mathematical functions are grouped in math module.
t 4. All String functions are grouped in String module.
s 5. To use a function, we have to import the required module.
: 6. To use function, we prefix the module name. Ex : math.sqrt(25)
Importing a Module
You can use any Python source file as a module by executing an import statement in some other
Python source file or in interactive mode. When a module is imported, Python runs all of the code in
the module file.
⮚ The import statement makes a module and its contents available for use.
⮚ The import statement evaluates the code in a module, but only the first time when any given
module is imported in an application.
⮚ A module is loaded only once, regardless of the number of times it is imported.
Python has a math module that provides most of the familiar mathematical functions. The
mathematical and trigonometric functions are prototyped in the math module. Be sure to import math
module at the top of any program that uses these functions. If you print the module object, you get
some information about it:
>>> import math
To access one of the functions you have to specify the name of the module and the name of the
function separated by a dot (also known as a period). This format is called dot (.) notation.
The following two examples produces the values of two mathematical constants π and e:
>>> import math
math.pi
3.141592653589793
math.e
The math e is a mathematical constant in python. It returns the value of Euler’s constant which is an
irrational number approximately equal to 2.71828. Euler’s constant is used in Natural Logarithms,
calculus, trigonometry, differential equations, etc.
>>> print (math.e)
value of math module 2.71828182845904
Remember that to use a math module, you must use the dot(.) notation with the module and
method
import math
For example,
Function
import math as at
The above statement imports only one method called sqrt() into the current application. For
example,
>>> import math as at
The above statement imports two methods sqrt and the value of a constant pi into the
current application.
We can write
The above statement imports all the methods from math module into the current
application. For example,
>>> from math import sqrt, pi
Function/method
Description
abs(number) This function returns the absolute value of a number. Absolute value
number can be of a number is the value without considering its sign.The argument
integer or
floating pt may be an integer or a
floating point number. No need for math module.
print (abs(-2.17)) # returns: 2.17
print (abs(2.17)) #returns 2.17
print (abs(-4)) #returns 4
print (abs(4)) #returns 4
ceil() This method returns ceiling value of x - the integer just greater than
or equal to x
import math
print (math.ceil(-2.17)) # returns: –2
print (math.ceil(2.17)) #returns 3
print (math.ceil(math.pi)) # returns: 4
print (math.ceil(2.00)) #returns 2
print(math.ceil(2)) #returns 2
floor() This method returns floor of x – the largest integer not greater than x.
import math
print (math.floor(-2.17)) # returns: –3
print (math.floor(2.17)) #returns 2
print (math.floor(math.pi)) # returns: 3
print (math.floor(2.00)) # returns: 2
print (math.floor(2)) # returns: 2
fabs() This method returns an absolute (positive) value of any numeric
expression. It always returns result in floating point.
This requires math module to be imported.
import math
print (math.fabs(-2.17)) # returns: 2.17
print (math.fabs(2.17)) #returns 2.17
print (math.fabs(math.pi)) # returns: 3.141592....
print (math.fabs(-4)) #returns 4.0
print (math.fabs(4)) #returns 4.0
exp() This method returns exponential of x. i.e., ex.
import math
print (math.exp(200.72)) # returns: 1.4845280488479078e+87
print (math.exp(math.pi)) # returns: 23.140692632779267
print(math.sqrt(144))
print (pow(2,3))
What will abs(-22) will return ?
Programming example
Quadratic Equation
Write a program to find the root of quadratic equation. A quadratic equation has the form ax2+ bx +
c = 0. An equation has two solutions for the value of x by the quadratic formula:
√𝒃𝟐−𝟒𝒂𝒄
x=−𝒃 ±
𝟐𝒂
Output:
Enter the coefficient of a: 3 Enter the coefficient of b: 4 Enter the coefficient of c: –2 The two roots are:
0.39, –1.72
Function Description
print(random.random()) returned
0.6195855083084717
randrange () This method generates an integer between its lower and upper argument.
random.randrange(start(opt),stop,step(opt))
opt means optional
Leaving off the random part, range(start, stop, step) will create a range of integers,
starting at “start”, and less than “stop”, and incremented in between by “step”.
Example:
range(2,11,2) = [2,4,6,8,10],
randrange(0,30,5) would return ONE of the numbers in [0, 5, 10, 15, 20, 25].
6.There is one slight difference when used with just two parameters. randint(x,y)
will return a value >= x and <= y, while randrange(x,y) will return a value >=x
and < y (n.b. not less than or equal to y)
7. There is a bigger difference if you use the additional parameter that randrange
can take … randrange(start, stop, step)
Example:
import random
r_number = random.randrange (50) # creates a random number between 0 –49
print (r_number)
r_number = random.randrange (100, 200)
print (r_number)
Example:
import random
Output:
Random number from 0-100 is : 26
Random number from 50-100 is : 58
Random number from 50-100 skip 5 is : 90
Another time Running the program generated the output:
Random number from 0-100 is : 15
Random number from 50-100 is : 64
Random number from 50-100 skip 5 is : 95
Ans: random()
Ans: random()
Ans: Randint()
Ans: randrange()
Ans: 1
displayed 48 and 124 (in my case).
randint() If you want a random integer number between two numbers, then use the
randint() function. This function accepts two parameters: a lowest and a highest
number. This function is best used in guessing number.
randint(start, end)
Example 1 of randint()
import random
displayed 43 in my case
Example 2 of randint(). WAP to generate a random number between any two positive integers, one
random number number between aany two negative integers, one random number between a
positive and a Negative integer.
import random
# Generates a random number between
# a given positive range
r1 = random.randint(0, 10)
print("Random number between 0 and 10 is " ,r1)
Output:
Random number between 0 and 10 is 3
Random number between -10 and -1 is -9
Random number between -5 and 5 is 5
Example 3:
The user gets three chances to guess the number between 1 and 6. If guess is correct user
wins, else loses the competition. Program should also display how many chances were
left when the user guesses right.
import random
x=random.randint(1, 6)
c=0 # c will keep count of how many times he/she has guessed.
flag = 0
while c<3 :
guess = int(input("Enter your guess"))
c=c+1
if (guess==x):
flag = 1
break # takes us out of loop as the number is guessed correctly
else:
print("Wrong Guess!!")
Output:
shuffle() This method is used to shuffle the contents of a list (that is, generate a
random permutation of a list in-place).
import random
Color = ['Cyan', 'Magenta', 'Yellow', 'Black'] random.shuffle(Color)
print ("Reshuffled color : ", Color) # prints: Reshuffled color : ['Yellow',
'Black', 'Magenta', 'Cyan']
random.shuffle(Color)
Output:
Reshuffled color : ['Yellow', 'Magenta', 'Black', 'Cyan']
Reshuffled color : ['Black', 'Cyan', 'Yellow', 'Magenta']
Function Description
mean() This function is used to find the arithmetic mean of a set of data (list, tuple, etc.)
which is obtained by taking the sum of the data and then dividing the sum by the total
number of values in the set. For example, if S = [8, 7, 10, 9, 6, 4, 11] is a list data-
set, then mean is:
8 + 7 + 10 + 9 + 6 + 4 + 11
𝑀𝑒𝑎𝑛 =
7
55
𝑀𝑒𝑎𝑛 =
7
import statistics
S = [8, 7, 10, 9, 6, 4, 11] # S is a list
Smean = statistics.mean(S)
print("Mean is :", Smean) # prints: Mean is : 7.857142857142857
that is halfway into the set. In Python, the median() function is used to
calculate the median or
middle value of a given set of numbers. Let us see an orderly odd data-set
with 5 values:
median
5 10 1 2 2
5 0 5
import statistics
S = [5, 10, 15, 20, 25]
Smedian = statistics.median(S)
Median
(Mean of
this two)
4 5 10 1 1 1 1 2
1 5 7 8 0
Since there is an even number of items in the data set, we find we find the
middle pair of
numbers and then find the value that is half way between them, i.e.,
compute the median by
taking the mean of the two middlemost numbers, i.e., (15 + 17) / 2 = 16.
import statistics
1 1 2 3 3 3 4
import statistics
X = [1, 1, 2, 3, 3, 3, 3, 4]
print ('Mode of X =', statistics.mode(X)) # prints: Mode of X = 3
# prints: Vimal
Note. If a data set contains two equally common values or an empty data set, then
the StatisticsError will be raised.