0% found this document useful (0 votes)
23 views

11 Notes Modules

Modules allow for organizing Python code into logical units and reusing code. The key points are: 1) Modules contain reusable functions that can be imported and used in other code. 2) Common mathematical, random, and statistical functions are grouped into modules like math, random, and statistics. 3) The import statement is used to import modules and their contents, making the functions accessible.

Uploaded by

Neha Parmanandka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

11 Notes Modules

Modules allow for organizing Python code into logical units and reusing code. The key points are: 1) Modules contain reusable functions that can be imported and used in other code. 2) Common mathematical, random, and statistical functions are grouped into modules like math, random, and statistics. 3) The import statement is used to import modules and their contents, making the functions accessible.

Uploaded by

Neha Parmanandka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MODULES IN PYTHON

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 importance of import statement is:

⮚ 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 imports are case-sensitive

The general format of import statement is:

import module_name1[, module_name2[,... module_nameN]

Importing Math Module

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

>>> print (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

• Most of the power of a programming language is in its libraries.


• A program must import a module in its library in order to use it.

Different implementations of import statement

Remember that to use a math module, you must use the dot(.) notation with the module and
method

name except abs() function.

import math

For example,

>>> import math

>>> print (math.sqrt(100)) # prints: 10.0


math Module
sqrt(), sin()
module Argument/
parameter

Function

import math as at

The above statement imports only one method called sqrt() into the current application. For
example,
>>> import math as at

>>> print (at.sqrt(100)) # prints: 10.0

from math import sqrt, pi

The above statement imports two methods sqrt and the value of a constant pi into the
current application.

We can write

from math import sqrt


For example,
>>> from math import sqrt, pi
>>> print (sqrt(100), pi) # prints: 10.0 3.141592653589793

from math import *

The above statement imports all the methods from math module into the current
application. For example,
>>> from math import sqrt, pi

>>> from math import *


>>> print (sqrt(100), pi, floor(10.91)) # returns: 0.0 3.141592653589793
Math function continues….

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

log() This method returns natural logarithm of x, for x > 0.


import math
print (math.log(1)) # returns: 0.0
print (math.log(10)) # returns: 2.302585092994046

log10() This method returns base-10 logarithm of x for x > 0.


import math
print (math.log10(1)) # returns: 0.0
print (math.log10(10)) # returns: 1.0

pow() This method returns the value of xy.


import math
print (math.pow(2, 4)) # returns: 16.0
print (math.pow(100, –2)) # returns: 0.0001
print (math.pow(3, 0)) # returns: 1.0
print (math.pow(3.5, 2)) #returns 12.25
print (math.pow(2, 0.5)) #returns 1.4

sqrt() This method returns the square root of x for x > 0.


import math
print (math.sqrt(144)) # returns: 12.0
print (math.sqrt(7)) # returns: 2.6457513110645907

cos() This method returns the cosine of x radians.


Import math
print ("cos(30) : ", math.cos(30)) # returns: 0.15425144988758405
print ("cos(0) : ", math.cos(0)) # returns: 1.0
sin() This method returns the sine of x, in radians.
Import math
print ("sin(30) : ", math.sin(30)) # returns: –0.9880316240928618
print ("sin(0) : ", math.sin(0)) # returns: 0.0
tan() This method returns the tangent of x radians.
Import math
print ("tan(30) : ", math.tan(30)) # returns: –6.405331196646276
print ("tan(0) : ", math.tan(0)) # returns: 0.0

degree() This method converts angle x from radians to degrees.


Note. The radian is a unit of measure for angles used mainly in trigonometry.
It is used instead of degrees. Whereas a full circle is 360 degrees, a full circle
is just over 6 radians.
Import math
print ("degrees(30) : ", math.degrees(30)) # returns:
1718.8733853924696
print ("degrees(0) : ", math.degrees(0)) # returns: 0.0

radians() This method converts angle x from degrees to radians.


import math
print ("radians(30) : ", math.radians(30)) # returns:
0.5235987755982988
print ("radians(0) : ", math.radians(0)) # returns: 0.0

Q) Write the output

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=−𝒃 ±

𝟐𝒂

# A program that compute the real roots of a quadratic equation.


import math # This will import math module
a = int(input("Enter the coefficient a: "))
b = int(input("Enter the coefficient b: "))
c = int(input("Enter the coefficient c: "))
discRoot = math.sqrt(b * b – 4 * a * c)
root1 = (–b + discRoot) / (2 * a)
root2 = (–b – discRoot) / (2 * a)
print()
print ("The two roots are:” ,root1, root2)

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

Using random module


Random numbers are heavily used in Computer Science for programs that involve games or simulations.
Python has a random module to generate random numbers.
>>> import random
>>> print (random)

Extra Info : <module 'random' from 'C:\\Python37\\lib\\random.py'>

Function Description

random() This function generates a random number from 0 to 1 including 0, but


excluding 1.
import random

print(random.random()) returned
0.6195855083084717

You can do computations like :


x=random.random()+4
will give random no like 4.877258696863911

randrange () This method generates an integer between its lower and upper argument.

random.randrange(start(opt),stop,step(opt))
opt means optional

1. start(opt) : Number consideration for generation starts


from this,default value is 0. This parameter is optional.
2. stop : Numbers less than this are generated. This
parameter is mandatory.
3. step(opt) : Step point of range, this won't be included.
This is optional.Default value is 1.

4. Randrange= generates the numbers in the sequence start-


stop skipping step.
5. Raises ValueError if stop <= start and number is non-
integral.

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 will return a random number that is contained in the list.

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

# Using randrange() to generate numbers from 0-100


print ("Random number from 0-100 is : ",end="")
print (random.randrange(100))

# Using randrange() to generate numbers from 50-100


print ("Random number from 50-100 is : ",end="")
print (random.randrange(50,100))

# Using randrange() to generate numbers from 50-100


# skipping 5
print ("Random number from 50-100 skip 5 is : ",end="")
print (random.randrange(50,100,5))

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

Which module generates floating point numbers?

Ans: random()

Which module doesn’t take arguments?

Ans: random()

Which module accepts exactly 2 arguments?

Ans: Randint()

Which module accepts 3 arguments?

Ans: randrange()

Which module returns numbers less than one?


Ans : random()

Which number cant be generated by random()- 0.1/0.12,0.5,1?

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)

1. (start, end) : Both of them must be integer type values.

2. Generates a random integer in range [start, end] including


the end points.

3. -ve integers may be passed as parameters ie. Start and


endpoint. One positive and one negative integer may be
passed.
4. ValueError : Returns a ValueError when floating
point values are passed as parameters.

5. TypeError : Returns a TypeError when anything other than


numeric values are passed as parameters.

Example 1 of randint()
import random

x = random.randint(1, 100) # Pick a random number between 1 and 100.


print(x)

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)

# Generates a random number between


# two given negative range
r2 = random.randint(-10, -1)
print("Random number between -10 and -1 is " ,r2)

# Generates a random number between


# a positive and a negative range
r3 = random.randint(-5, 5)
print("Random number between -5 and 5 is " , r3)

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!!")

if flag==1: # the loop was exited with correct guess


print("You guessed correct")
print("You had ",3-c,"chances left")
else:
print("You couldnt guess")
print("Better Luck Next time")
print("The number guessed by computer was ",x)

Output:

Enter your guess4


Wrong Guess!!
Enter your guess5
Wrong Guess!!
Enter your guess2
Wrong Guess!!
You couldnt guess
Better Luck Next time
The number guessed by computer was 6
choice() This method is used for making a random selection from a sequence like a
list, tuple or string.
import random
MyChoice = random.choice(['1-Swimming', '2-Badminton', '3-Cricket', '4-
Basketball', '5-Hockey'])
print ('My choice is:', MyChoice) #
returns: My choice is: 4-Basketball
Note. Remember that this function return any of the list element.

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)

print ("Reshuffled color : ", Color )

Output:
Reshuffled color : ['Yellow', 'Magenta', 'Black', 'Cyan']
Reshuffled color : ['Black', 'Cyan', 'Yellow', 'Magenta']

Another time Run :


Reshuffled color : ['Magenta', 'Black', 'Yellow', 'Cyan']
Reshuffled color : ['Black', 'Yellow', 'Cyan', 'Magenta']

Program : WAP to display a real number between 0 and 1.


import random
r= random.random()
print(r)

Program : WAP to display a real number between 5 and 10.


import random
r= random.random()*5+5
print(r)
Using statistics module
Python statistics module is used to calculate mathematical statistics of numeric (Real- valued) data.
To access Python's statistics functions, we need to import the statistics module. To import all statistics
module:
>>> import statistics

>>> print (statistics)

<module 'statistics' from 'C:\\Python37\\lib\\statistics.py'>

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

Note. If a data set empty, then the StatisticsError will be raised.

>>> import statistics

>>> print (statistics)

<module 'statistics' from 'C:\\Python37\\lib\\statistics.py'>


Description

The median of a set of data is


the middlemost number in the set. The median is also the number

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)

print("Median is :", Smedian) # prints: Median is : 15

Let us see an orderly even data-set with 10 values:

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

X = [4, 5, 10, 11, 15, 17, 18, 20, 22, 25]


print ('Median of X =', statistics.median(X)) # prints: Median of X = 16.0

Note. If a data set empty, then the StatisticsError will be raised.


Funct Description
ion
mo In statistics, the mode of a set of data is the value in the set that occurs most often.
de( The mode() in function Python is used to calculate the mode of given continuous
) numeric or nominal data.

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

Let us see another example with data-set of string values:

Name = ('Anmol', 'Kiran', 'Vimal',


'Sidharth', 'Riya', 'Vimal')
print(statistics.mode(Name))

# prints: Vimal

Note. If a data set contains two equally common values or an empty data set, then
the StatisticsError will be raised.

You might also like