[Go to site: main page, start]

0% found this document useful (0 votes)
13 views13 pages

8-Python 08 PythonModules

The document provides an overview of Python modules, explaining their purpose, how to import them, and examples of using the math, random, and statistics modules. It details various functions available in these modules, including mathematical operations and statistical calculations. Additionally, it includes a programming example for solving a quadratic equation using the math module.

Uploaded by

akshat1949
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views13 pages

8-Python 08 PythonModules

The document provides an overview of Python modules, explaining their purpose, how to import them, and examples of using the math, random, and statistics modules. It details various functions available in these modules, including mathematical operations and statistical calculations. Additionally, it includes a programming example for solving a quadratic equation using the math module.

Uploaded by

akshat1949
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 string 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.

Reeta Sahoo & Gagan Sahoo


Importing Python 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]

Reeta Sahoo & Gagan Sahoo


Using 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
>>> print (math)
<module 'math' (built-in)>

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
>>> print ([Link]) # Prints individual object value of math module
3.141592653589793
>>> print (math.e) # Prints individual object value of math module
2.718281828459045

Reeta Sahoo & Gagan Sahoo


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 ([Link](100)) # prints: 10.0
Import math as at
The above statement imports only one method called sqrt() into the current application.
For example,
>>> Import math as at
>>> print ([Link](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.
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 10
Math function continues….

Function Description
abs() This function returns the absolute value of a number. The argument may be an integer or a
floating point number. No need for math module.
print (abs(–55)) # returns: 55
print (abs(200.12)) # returns: 200.12
ceil() This method returns ceiling value of x - the smallest integer not less than x.
Import math
print ([Link](–55.17)) # returns: –55
print ([Link]([Link])) # returns: 4
floor() This method returns floor of x – the largest integer not greater than x.
Import math
print ([Link](200.12)) # returns: 200
print ([Link]([Link])) # returns: 3
fabs() This method returns an absolute (positive) value of any numeric expression.
Import math
print ([Link](200.72)) # returns: 200.72
print ([Link]([Link])) # returns: 3.141592653589793
exp() This method returns exponential of x. i.e., ex.
Import math
print ([Link](200.72)) # returns: 1.4845280488479078e+87
print ([Link]([Link])) # returns: 23.140692632779267
log() This method returns natural logarithm of x, for x > 0.
Import math
print ([Link](1)) # returns: 0.0
print ([Link](10)) # returns: 2.302585092994046
Math function continues….

Function Description
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 ([Link](2, 4)) # returns: 16.0
print ([Link](100, –2)) # returns: 0.0001
print ([Link](3, 0)) # returns: 1.0
sqrt() This method returns the square root of x for x > 0.
Import math
print ([Link](144)) # returns: 12.0
print ([Link](7)) # returns: 2.6457513110645907
cos() This method returns the cosine of x radians.
Import math
print ("cos(30) : ", [Link](30)) # returns: 0.15425144988758405
print ("cos(0) : ", [Link](0)) # returns: 1.0
sin() This method returns the sine of x, in radians.
Import math
print ("sin(30) : ", [Link](30)) # returns: –0.9880316240928618
print ("sin(0) : ", [Link](0)) # returns: 0.0

Reeta Sahoo & Gagan Sahoo


Math function continues….

Function Description
tan() This method returns the tangent of x radians.
Import math
print ("tan(30) : ", [Link](30)) # returns: –6.405331196646276
print ("tan(0) : ", [Link](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) : ", [Link](30)) # returns: 1718.8733853924696
print ("degrees(0) : ", [Link](0)) # returns: 0.0
radians() This method converts angle x from degrees to radians.
Import math
print ("radians(30) : ", [Link](30)) # returns: 0.5235987755982988
print ("radians(0) : ", [Link](0)) # returns: 0.0

Reeta Sahoo & Gagan Sahoo


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:
−𝒃 ± 𝒃𝟐 − 𝟒𝒂𝒄
𝒙=
𝟐𝒂
# A program that compute the real roots of a quadratic equation.
import math # This will import math module
print()
a = int(input("Enter the coefficient of a: "))
b = int(input("Enter the coefficient of b: "))
c = int(input("Enter the coefficient of c: "))
discRoot = [Link](b * b – 4 * a * c)
root1 = (–b + discRoot) / (2 * a)
root2 = (–b – discRoot) / (2 * a)
print()
print ("The two roots are: %0.2f, %0.2f" % (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 Reeta Sahoo & Gagan Sahoo
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)
<module 'random' from 'C:\\Python37\\lib\\[Link]'>

Function Description
random() This function generates a random number from 0 to 1 including 0, but excluding 1.
from random import random
random() # returns: 0.1916168207727299
random() # returns: 0.689060949995414
randrange() This method generates an integer between its lower and upper argument.
import randrange
r_number = [Link] (50) # creates a random number between 0 – 49
print (r_number) # returns: 13
r_number = [Link] (100, 100)
print (r_number) # returns: 150
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.
import random
print ([Link](0, 5)) # returns 4
Note. Remember that this function return any of the number either 0, 1, 2, 3, 4 or 5.
Random function continues….

Function Description
choice() This method is used for making a random selection from a sequence like a list, tuple or string.
import random
MyChoice = [Link](['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']
[Link](Color)
print ("Reshuffled color : ", Color) # prints: Reshuffled color : ['Yellow', 'Black', 'Magenta', 'Cyan']
[Link](Color)
print ("Reshuffled color : ", Color ) # prints: Reshuffled color : ['Black', 'Cyan', 'Yellow', 'Magenta']

Reeta Sahoo & Gagan Sahoo


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\\[Link]'>

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 = [Link](S)
print("Mean is :", Smean) # prints: Mean is : 7.857142857142857

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


Statistics function continues….

Function Description
median() 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 15 20 25

import statistics
S = [5, 10, 15, 20, 25]
Smedian = [Link](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 11 15 17 18 20 22 25

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 =', [Link](X)) # prints: Median of X = 16.0
Note. If a data set empty, then the StatisticsError will be raised.
Statistics function continues….

Function Description
mode() In statistics, the mode of a set of data is the value in the set that occurs most often.
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 =', [Link](X)) # prints: Mode of X = 3

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

Anmol Kiran Vimal Sidharth Riya Vimal

Name = ('Anmol', 'Kiran', 'Vimal', 'Sidharth', 'Riya', 'Vimal')


print([Link](Name)) # prints: Vimal

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

Reeta Sahoo & Gagan Sahoo

You might also like