Introduction to Python Modules
Introduction to Python Modules
Introduction to Python Modules
INTRODUCTION
A large and complex program should be divided into files/functions that perform a specific
task called module.
module is simply a file that contains Python code. When we break a program into modules,
each module should contain functions that perform related tasks.
This approach, which is called modularization, makes the program easier to understand, test
and maintain.
Commonly-used modules that contain source code for generic needs are called libraries.
Therefore, when we speak about working with libraries in Python, we are, in fact, working
with modules that are created inside the package(s) or say, library.
A module is a file containing Python definitions, functions, variables, classes and statements
with .py extension.
A module name is the file name with the .py extension. When we have a file named empty.py,
empty is the module name. The __name__ is a variable that holds the name of the module being
referenced.
The current module, the module being executed (also called the main module), has a special
name: ‘__main__’. With this name, it can be referenced from the Python code.
A module’s file name should end in .py. If the module’s file name does not end with .py as the
extension, we will not be able to import it into other programs. A module’s name cannot be the
same as a Python keyword. Naming a module as ‘for’, ‘while’, etc., would result in an error.
To import the module into other modules or into the main module using any of the following
three constructs:
(i) “import” statement can be used to import a module. It is the simplest and most common
way to use modules in our code. It gives access to all attributes (like variables,
constants, etc.) and methods present in the module.
import <module_name>
In case of accessing specific modules, it can be modified as:
import module1[, module2 [, ...moduleN]
To access particular methods from any module, the statement shall be:
<module_name>.<function_name>
(ii) Python’s from statement lets us import specific attributes or individual objects from a
module into the current (calling) module or namespace.
from <module_name> import <function_name(s)>
Or
from <module_name> import function_name1
[,...function_name2[,...function_nameN]]
To use/access/invoke a function, we will specify the module name and name of the function
separated by a dot (.). This format is also known as dot notation.
<module_name>.<function_name>
(iii) import * statement can be used to import all names from a module into the current calling
(namespace) module.
from <module_name> import*
Note: We can access any function which is inside a module by module name and function name
separated by a dot, i.e., using dot notation.
Example 1: Let’s say we have a Python file called area.py which has a few functions in it for
calculating the area of a circle, square and rectangle. Use those functions again in some other
programs.
When we will run this program, the sub-modules, namely circle_area(), square_area() and
rectangle_area(), shall be called from module area using the statements:
area.circle_area()
area.square_area()
area.rectangle_area()
Retrieving objects from a Module
There is another function dir() which, when applied to a module, gives you the names of all
that is defined inside the module.
import * statement
STANDARD BUILT-IN PYTHON MODULES
BUILT-IN FUNCTIONS
For example,
>>> print("math.ceil(3.4):", math.ceil(3.4))
Output: math.ceil(3.4): 4
y
pow(x,y): It returns the value of x , where x and y are numeric expressions.
>>> print("math.pow(3, 3):", math.pow(3, 3))
math.pow(3, 3): 27.0
>>> math.pow(100, –2)
0.0001
>>> math.pow(2, 4)
16.0
>>> math.pow(3, 0)
1.0
For example,
>>>print(math.fabs(500.23))
500.23
>>>print(math.fabs(-200))
200
>>>print(math.fabs(-15.6343))
15.6343
help function
If you forget how to use a standard function, Python's library utilities can help. In this case,
Python's help() library functions is extremely relevant. It is used to know the purpose of a
function and how it is used.
For example,
>>>import math
>>>print(help(math.cos))
Help on built-in function cos in module math:
cos(...)
None
cos(x)
Return the cosine of x (measured in radians).
In Python, random numbers are not enabled implicitly; therefore, we need to invoke random
module explicitly or to invoke random code library in order to generate random numbers.
• import statement is the first statement to be given in a program for generating random
numbers:
import random
The various functions associated with this module are explained as follows:
randrange(): This method generates an integer between its lower and upper argument. By
default, the lower argument is 0.
For example,
ran_number = random.randrange(30)
Alternatively,
This line of code shall generate random numbers from 0 to 29. Let us see another example:
Example 1: To select a random subject from a list of subjects.
random()
This function generates a random number from 0 to 1 such as 0.5643888123456754. This
function can be used to generate pseudorandom floating point values. It takes no parameters
and returns values uniformly distributed between 0 and 1 (including 0, but excluding 1). Let us
take some examples to gain better clarity about this function:
Example 2:
randint()
This function accepts two parameters, a and b, as the lowest and highest number; returns a
number ‘N’ in the inclusive range [a,b], which signifies a<=N<=b, where the endpoints are
included in the range. This function generates a random integer number between two given
numbers. This function is best suited for guessing number applications. The syntax is:
random.randint(a,b)
Here, a is the lower bound and b is the upper bound. In case you input a number N, then the
result generated will be a <= N <= b. Please make sure that the upper limit is included in
randint() function.
Example 3: To generate a number between 0 and 9.
Statistics module
The statistics module implements many common statistical formulas for efficient calculations
using Python’s various numerical types (int, float, Decimal, and Fraction).
mean(): The mean() method calculates the arithmetic mean of the numbers in a list.
For example,
>>> import statistics
>>> statistics.mean([4,6,7,8,10,45])
13.333333333333334
median(): The median() method returns the middle value of numeric data in a list. This
function finds the centre value, and if the data set has an even number of values, it
averages the two middle items.
For example,
>>> import statistics
>>> statistics.median([1,2,3,8,9])
3
>>> statistics.median([1,2,3,7,8,9])
5.0