Introduction to Python Module – Notes

Topics:

  • Introduction to Python modules:
  • Importing module using ‘import ‘ 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)

Module

A module is a grouping of functions. The program is divided into different parts under different levels, called modules.

Also, suppose we have created some functions in a program and we want to reuse them in another program. In that case, we can save those functions under a module and reuse them.
A module is created as a python (.py) file containing a collection of function definitions.

Import Statement

To use a module, we need to import the module. Once we import a module, we can directly use all the functions
of that module.

The syntax of import statement is as follows:
import modulename1 [,modulename2, …]
This gives us access to all the functions in the module(s).

To call a function of a module, the function name should be preceded with the name of the module with a dot(.) as a separator.
The syntax is as shown below:
modulename.functionname()

Built-in-Module

Python library has many built-in modules that are really handy to programmers. Let us explore some commonly used modules and the frequently used functions that are found in those modules:
• math
• random
• statistics

Module name : math
It contains different types of mathematical functions.
Most of the functions in this module return a float value.
In order to use the math module we need to import it using the following statement:
import math

Some of the commonly used functions in math module are given in Table.

Function
Syntax
ArgumentsReturnsExample
Output
math.ceil(x)x may be an integer or
floating point number
ceiling value of xmath.ceil(-9.7)
-9
math.ceil (9.7)
10
math.ceil(9)
9
math.floor(x)x may be an integer or
floating point number
floor value of xmath.floor(-4.5)
-5
math.floor(4.5)
4
math.fabs(x)x may be an integer or
floating point number
absolute value of xmath.fabs(6.7)
6.7
math.fabs(-6.7)
6.7
math.fabs(-4)
4.0
math.factorial(x)x is a positive integerfactorial of xmath.factorial(5)
120
math.fmod(x,y)x and y may be an
integer or floating point
number
x % y with sign of xmath.fmod(4,4.9)
4.0
math.fmod(4.9,4.9)
0.0
math.fmod(-4.9,2.5)
-2.4
math..fmod(4.9,-4.9)
0.0
math.gcd(x,y)x, y are positive integersgcd (greatest common
divisor) of x and y
math.gcd(10,2)
2
math.pow(x,y)x, y may be an integer or
floating point number
xy (x raised to the
power y)
math.pow(3,2)
9.0
math.pow(4,2.5)
32.0
math.pow(6.5,2)
42.25
math
math.sqrt(x)x may be a positive
integer or floating point
number
square root of xmath.sqrt(144)
12.0
math.sqrt(.64)
0.8
math.sin(x)x may be an integer or
floating point number in
radians
sine of x in radiansmath.sin(0)
0
math.sin(6)
-0.279

Module name : random

This module contains functions that are used for generating random numbers.

For using this module, we can import it using the following statement:
import random

Some of the commonly used functions in random module are given in Table.

Function
Syntax
ArgumentReturnExample
Output
random.random()No argument
(void)
Random
Real Number
(float) in the
range
0.0 to 1.0
random.random()
0.65333522
random.
randint(x,y)
x, y are integers
such that
x <= y
Random integer
between x and y
random.randint(3,7)
4
random.randint(-3,5)
1
random.randint(-5,-3)
-5.0
random.
randrange(y)
y is a positive integer
signifying the stop
value
Random integer
between 0 and y
random.randrange(5)
4
random.
randrange(x,y)
x and y are positive
integers signifying
the start and stop
value
Random integer
between x and y
random.randrange(2,7)
2

Module name : statistics

This module provides functions for calculating statistics of numeric (Real-valued) data. It can be included in the program by using the following statements:
import statistics

Some of the commonly used functions in statistics module are given in Table :-

Function SyntaxArgumentReturnExample
Output
statistics.mean(x)x is a numeric
sequence
arithmetic
mean
statistics.
mean([11,24,32,45,51])
32.6
statistics.median(x)x is a numeric
sequence
median
(middle
value) of x
statistics.
median([11,24,32,45,51])
32
statistics.mode(x)x is a sequencemode
(the most
repeated
value)
statistics.
mode([11,24,11,45,11])
11
statistics.
mode((“red”,”blue”,”red”))
‘red’

Important points regarding Import Statement:

  • import statement can be written anywhere in the program
  • Module must be imported only once.
  • In order to get a list of modules available in Python, we can use the following statement: help(“module”)
  • To view the content of a module say math, type the following: help(“math”)
  • The modules in the standard library can be found in the Lib folder of Python.

From Statement

Instead of loading all the functions into memory by importing a module, from statement can be used to access only the required functions from a module.

It loads only the specified function(s) instead of all the functions in a module.
Its syntax is :

from modulename import functionname [,functionname,…]
To use the function when imported using “from statement” we do not need to precede it with the module name.

Rather we can directly call the function as shown in the following examples:

Example-

>>> from random import random
>>> random() #Function called without the module name
Output:
0.9796352504608387
Example –
>>> from math import ceil, sqrt
>>> value = ceil(624.7)
>>> sqrt(value)
Output:
25.0

Composition

A programming statement wherein the functions or expressions are dependent on each other’s execution for achieving an output is termed as composition.

Example :

>>> sqrt(ceil(624.7))

>>> sqrt(trunc(625.7))

a = int(input("First number: "))
print("Square root of ",a ," = ",math.sqrt(a))
print(floor(a+(b/c)))
math.sin(float(h)/float(c))

Creating a User Define Module

In Python standard library, we can also create our own module consisting of our own functions.

Create a user defined module basic_math that contains the following user defined functions:

  1. To add two numbers and return their sum.
  2. To subtract two numbers and return their difference.
  3. To multiply two numbers and return their product.
  4. To divide two numbers and return their quotient and print “Division by Zero” error if the denominator
    is zero.
  5. Also add a docstring to describe the module. After creating module, import and execute functions.

The requirement is:

1. Write a docstring describing the module.

2. Write user defined functions as per the specification.

3. Save the file.

4. Import at shell prompt and execute the functions.

"""
 basic_math Module
 
 This module contains basic arithmetic operations
 that can be carried out on numbers
 """
 Beginning of module
 def addnum(x,y):
     return(x + y)
 def subnum(x,y):
     return(x - y)
 def multnum(x,y):
     return(x * y)
 def divnum(x,y):
     if y == 0:
        print ("Division by Zero Error")
     else:
       return (x/y) #End of module
     
Output:
 # Statements for using module basic_math
 >>> import basic_math
 # Display descriptions of the said module
 >>> print(basic_math.doc)
       basic_math Module
       ******************
This module contains basic arithmetic operations that can be carried out on numbers

>>> a = basic_math.addnum(2,5) #Call addnum() function of the
>>> a #basic_math module
     7
>>> a = basic_math.subnum(2,5) #Call subnum() function of the
>>> a #basic_ math module
    -3
>>> a = basic_math.multnum(2,5) #Call multnum() function of the
>>> a #basic_math module
    10
>>> a = basic_math.divnum(2,5) #Call divnum() function of the
>>> a #basic_math module
    0.4
>>> a = basic_math.divnum(2,0) #Call divnum() function of the
 Zero Divide Error #basic_math module     

doc variable stores the docstring. To display docstring of a module we need to import the module and type the following:
print(<modulename>._ _doc_ _) #_ _ are 2 underscore without space

Leave a Comment

You cannot copy content of this page

Scroll to Top