introduction to python module Preeti arora
introduction to python module Preeti arora
Python Modules
9.1 INTRODUCTION
As our programs become bigger and more complex,
the need to organize our code becomes greater. A
large and complex program should be divided into scientific
conputing
files/functions that perform specific tasks. As we
write more and more functions in a program, we Python NumPy
should consider organizing them by storing them in
modules. data
GUI visualization
A module is simply a file that contains a Python Tkinter PlotLib
code. When we break a program into modules,
each module should contain functions that perform game
Web
development natural
related tasks. For example, suppose we are writing framework Pygame language
processing
an accounting system. We would store all the Django nltk
molecular
biology
account receivable functions in their own module Biopython
and the account payable functions and all the payroll
functions in their respective modules. Thisapproach, Fig. 9.1: Python Libraries
called mnodularization, makes a program easier to
understand, test and maintain.
bven tiny real-world applications contain thousands of lines of code. In fact, applications that
contain millions of lines of code are somewhat common. Imagine trying to work with a file large
hough to contain millions of lines of code--you would never find anything. In short, we need some
nethod to organize the codeinto smaller pieces that are easy to manage, much like the examples
this book. The Python solution is to place the code in separate code groupings called modules.
Commonl
Therefore,y-uwhen
sed modules that contain source code for generic needs are called libraries.
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. Thus, aPython program comprises
three main components:
Library or Package
Module
Functions/Sub-modules
Relation between a module, package and python
library in Python: Package
module is afilecontaining Python definitions,
A
functions, variables,classes and statements with
py extension.
On the other hand, a Python package is simply Modules
a directory of Python module(s).
Alibrary in Python is acollection of various
packages. Conceptually, there is no difference
between a package and Python library. In
Python, a library is used to loosely describe a
collection of core or main modules. Fig. 9.2: Relation between a Package and Madii
Module Names
with A module name is the file name with the.py extension. When we have afile named emptypy, emp
is the module name. The_name is a variable that holds the name of the module being referenceu
Science
module), has a speca
The current module or the module being executed (also called the main
name:_main__ With this name, it can be referenced from the Python code.
Gomputer module's file name does not end with Py
A module's file name should end with .py. If the
programs. Amodule name canne
the extension, we will not be able to import it into other
as a Python keyword. Naming a module as 'for, 'while, etc., will result in an erro
the same
MPORTING PYTHON MODULES
g
comO way to create a module is to definea separate file containing the code we
separately from the rest of the application For eample, we might want to Create
troutinethat an application uses in a number of places. The print routine is not designed
own but is part of the application as a whole. We want to separate it because the
Bses it at numerous places and we could potentially use the samecode in another
The ability to reuse code ranks high on the list of reasons to create modules
Woaliesaso make it easy to reuse the same code in more than one program. IfEwe have written
unctions that is needed in several different programs, we can place those functions
le Then, we can import the module in each program that needs to call one of the
sThere are different wzys by which we can import a module We can use any Python
Efle as 2module by executing an import statement
isd brary of Python is extended as module(s) to a programmer. Definitions from the
le can be used within the code of aprogram. To use these modules in a program, a
needs to import the module into other modules or into the main module using
aT of the following three constructs
(0 mport statement can be used to import a module. It is the simplest and most
common way to use modules in our code. It provides access to all attributes (ie
variables, constants, etc) and methods present in the module
import <hOdule name
in case of 2ccessing specific modules, it can be modified as
import odulel [, module2 E, -. .moduleN)
To 2ccess particular methods from any module, the statement shall be
<module name>.<Íunction name>
Python's from statement lets us import speciñc attributes or individual objects frot
2module into the current (calling) module or namespace.
from <module name> inport <function_name (s) >
Or
irom <odule name> import function namel
L-..function name2 [, -. .function_nameN)I
se/access/ invoke a function, we willspecify the module name and the name of the tunction
Searated by adot () This format is also known as dot notation.
Cmodule name>.<function name>
j import statement can be used to import all names from amodule into the curent
calling (namespace) module.
irom <module name> import
Note Wie can access any function which is inside a module by module name and function name
separated by a dot, ie, using dot notation.
83
Example 1: Suppose
few simple
we examples.
have a Python file named area.py which has a few functions in it for
Let us look at a
calculatingthe area of a circle, square and rectangle. Use those functions again in Some other
sers/preeti/AppData/Local/Programs/Python/Python
programs. tareapy Window Help
Run Ogptions
Fle Edit Fomat module- "area.py"
area
#To develop #importing math library
import math
(radius) :
def circle area
#pitr*r
return math.pi *radius#radius
(side)
def square area
#side side
return sidetside
area(length, breadth) :
det rectangle breadth
#length
return length*breadth
Lnc 18 Cot 0
inport area
print (area.circle area (5) icalling the submodule circle area from module area
print (area.square_area (10)) The import statement gives access
print (area.rectangle_area (20,40)) to all attributes and methods present
in a module.
Methods in a module are accessed
using syntax: module.method ()
RESTART: C:/Users/preeti/AgpData/Local/Programs/P
ython/Python3 é-32/mathl.py
78.53981633974483
200
800
RESTART: Ci/Users/preeti/AppData/Bee/gra
3/Python/Python36-32/math2py
314.1592653589793
(sub-routine) from a mod
from..import statement is used to import a particular attribute
imported, then you can use fron
In case you do not want the whole of the module to be
calculate area of the circl
import statement as we have done in the above example. In order to
circle_area() function is being called from module "area'.
instead of impor
CTM: For modules having a large number of functions, it is recommended to use from
Now let us see the third format of importing a module using from...import.
The import* statement allows a user to import everything from the file or mnodule, Thie
construct will import all Python definitions into the namespace of another module.
However, this construct is not recommended to be used much as it may result in namespace
pollution. We may have several objects of the same name and their definitions can be overridden.
Example 4: Modification of Example 3-to import all the sub-modules from module "area"
Lmath3.py - C/Users/preeti/App Data/Local/Programs/P
File Edit Format Run Options Window Help
# Use of import * statement
import * gives
from area import * access to all functions
in area module
print (circle area(12) ) Youcan use all the
print (square area (20) ) functions in area
print (rectangle area (25,15) )
module directly
Ln: 8 Cok 4
Computer <module_name>,<name>
sub-module/any object
9.6
textiport* When yo 8e
robjects detinedin the module Tesiyort stateHent, it ahattimart att the
no the eurrent
are requited to xiply give xwb Hetex
statement,
the module test hother wort,
namexpave
he name t the ahjevt t beN%, affer eeeutng h
yecifvng module' Name (ie, names woutit How he et as HaHe refred o, teined
test.ane ix not required to he given), t name was wthaut
defined, it is eplaced hy the nevW
nty,
) hom test import t2,3 Thix
version, the one mported hun the madute aleady
statement shall mport the module Learntns Ttpi Whenever we e Hne
(ext and create eterences in the wedite
urent namespace to the given obhjects, will
Ibe generated and srered n he hard
permmanenty k
ln other words, you nnoW HNe th
, and t3 in your program without
secifving their modle's name along with them
9.4 MODULE ALIASING
lou can create an alias when you import a module by
povides the salient feature of renaming a module at the using the as keyword, Thus, Pythan
time of inport
Syntax:
Practical Inmplementation-1
Develop a program caleulator for performing addition and multiplieation
modules and importing these mnodules in the program. operations using
As is evident from the same output obtained from the above two programs, wWe can say that
alias name works well with Python modules.
Here, test is the original module name and m the alias name. We can easily access members d
the main module by using the alias name m.
9.8
Practical lmplementation-4
program in Python that calculates the following:
Writea
a circle
. Area of
Circumference ofa circle
rectangle
. Area of a
Perimeter of a rectangle
modules for each of the operations and call them separately using a
Create respective
menu-driven program.
program: those related
nhere are obviously two categories of calculations required in this
tocircles, and
those related to rectangles. You could write all circle-related functions in one
another module.
module and all rectangle-related functions in
circle Module
circle,py - C/Users/preeti/AppData/Local/Programs/Python/Python36-32/ci.-x
File Edit Format Run Options Window Help
La 17 Cok O
9,10
MENU
1. Area of a circle
2. Circunference of a circle
3. Area of a rectangle
4. Perimeter Of a
5. Quit rectangle
Enter your choice :4
Enter the rectangle's width: 20
Enter the rectangle's
The perimeter is 124 length: 42
MENU
1. Area of a circle
2.
Circunference
3. Area of a
of a circle
4. rectangle
Perimeter
5. Quit
of a rectangle
Enter your choice :1
Bnter the circle' s radius: 10
The area is
MENU
1. Area of a
314.1592653589793
2.
circle
Circumference
3. Area of a rectangle
oí a
circle
4. Perimeter of a
5. Quit rectangle
Enter your choice :5
Wodulescan Modules
) Built-jn be
categorized into the following two types:
User-defined Modules 9.11
detail.
discuss built-inmodules in
Let us
9.7.1 BUILT-IN Functions
predefined functions that are already available in Python,.
functions are
provide efficiency and structure to aprogramminglanguage. Python has many useful
Built-in
powerful. These are
casier, faster, and more
functions to make programming
inthe standard library and for using them, we don't have toimport any module (file),always avalase
Let us discuss math and datetime modules which are one of the most commonly used bui
modules in Python.
To access/use any of the functions present in the imported module, you have to specify te
name of the function, separated by a dot (also
name of the module followed by the
notation.
a period). This format is called dot
For example,
result math. sqrt (64) |Gives output as 8which gets
stored in variable 'result'
sqrt() is one of the functions that belongs to math module. This function accepts an argume
and returns the square root of the argument. Thus, the above statement calls the sort
passing 64 as an argument and returns the square root of the number passed as the argumes
ie, 8, which is then assigned to the variable 'result.
math Module
Let us understand a few more functions from the
math module.
Module
pie
math
sqrt function
sin function
Interpreter cos function
import math
Source code
Fig. 9.4: math
import math #the very Module in Python
first statement to be
ceil(x): Returns the given
For example, smallest integer that is greater than or equaltox.
>>> print
Output: ("math.ceil (3
.4):",4 math. ceil (3.4))
math.ceil (3.4):
floor(x):mathReturns the largest
>>>
-46 .floor (-45,17) integer that is less than or equalto x.
>>> math.floor (100,12)
100
9.12 >>> math.floor (100.72)
100
value of X, where Xand y
It returns the
>>>print ("nath.pow (3,
3) : math are numerie
Tath.po33) : 27,0 .pow (3, 3)) expressions,
>> 1ath.pow (100, -21
.0002
>>> math.pow(2, 4)
16.0
>>> nath.pow(3, O)
1.0
.9899924966004454
nath.cos ()
Bath.cos s(math.pi)
of x in radians.
G sin(x): Returns the sine
>>> math.sin (3)
0.14112000806
>>> math.sin (-3)
-0.14112000806
>>> math. sin (0)
0.0
help function
If you forget how to use a standard function, Python's library
utilities can help. Iht
case, Python's help(0 library function is extremely relevant. It is used to know be
purpose of a function and how it is used.
For example,
>>> import math
>>> print (help(math. cos) )
Help on built-in
cos (.. .)
function cos in module matn:
None
cOs (x)
Return the cOsine of X (measured in radians).
random Module (Generating
The programming concepts weRandom Numbers)
have learnt so far involved situations where we Wereawa
the definite output to be obtained when a particular task was to be executed, whichisder
as a deterministic approach. But there are certain situations//applicationsthatinvolve
gae
simulationsare which work on a rai
SItuations
numbers extensively used non-det such as:erministic approach. In these types of:
1,
2. Pseudorandom
Recaptcha(like numbers on lottery
in login forms) uses scratch
a random number generatorto define which in¡
to be cards.
shown to the user.
3.
Computer games involving
4. ac
"lipping
library in order to
generate
import random statement to be given in a generatingrai
9.14 program O
AHctions asxoclated with this% module are as follows:
ndrange(): Thix method generates an integer between its
agumen y detault, the lower argument is 0, lower and upper
Awevample,
hunber random, randrange (30)
Ahewntveb,
an number -random, randrange (30) >>> import random
print (ran humber) >>> random.randrange (30)
13
ThN neofcode shall generate random numbers from 0to 29. Let us take another example:
Nample $: 70 select a random subject from a list of subjects.
denoy CUsers/oree/ABbata/toca/Programs/python/Python36-32/radn.X
# detonatrate randrange ()
select a andom aubject from a list of subjects
AMort random
ubject8 ("Computer Seience", "IP", "Physics", "Accountancy"]
ran index random, randrange (2)
print (subjecta [ran index)) RESTART: C:/Users/preeti,
rams/Python/ Python36-32/r
Computer Science
random)
This tunction generates a random number from 0 to 1 such as 0.5643888123456754.
This unction can be used to generate pseudorandom floating point values. It takes
hoparameters and returns values uniformly distributed between 0and 1(including
0, but excluding 1). Let us take some examples to gain better clarity about this
function:
Lxample 6:
ython 3.6.S Shell
Fle tt Shell Debug Options Windew Help
Python 3.6.5 (3.6.5:£59c0932b4, Mar 28 2018, 16 ^
07146) (NSC V. 1900 32 bit (Intel) ) on win32
ype "copyright", "credits" or "license () " tor m Modu
Ore intormation .
S>> from random import random
>>> random ()
0.1353092847401708
>>> random () Pytho
0,9198861501740009
Ln Col4
to
ONT TO REMEMBER Intro
Nis lis to be keptin mind that every time we areexecutingthis program, it shal display adifferent value
|%
tAsisanevident
dom) methodrom thealwaysabovepiocksstatements, each time random() generates adifferent number,
up any value from the given range.
he random) function can also be written with the following alternative approach: 9.15
digits of a random
calculate the sum of the
Example 7: Program to
three-digit number.
Grad sumofdigitspy-CUsers/preeti/AppData/Local/Programs/Python/Python36-32/taddsumoOx
File Format Run Options
Window Help
#To calculate the sum of the digits of a random three--digit number
import random
from random >>>
Explanation:
number
The random() function generates a random fractional between 0and 1.
random numberWhenis random
a
number generated using random() gets multiplied by 900, a
between 0 and 899. When you add 100 to it, you get a number between 100 and 999. obtained
Then, the fractional part gets discarded using int) and gets printed on the shell windov t
the next statement, the first digit (the most significant) of the number is extracted by
it with 100 (a = n//100). dividing
The last digit of the number is extracted by dividing it by 10. The remaining number then gt
divided by 10 and the quotient is again mod with 10 to get ten's digit and the remainder is agzin
mod with 10 and this process gets repeated till all the digits are extracted and finally adied
together. In the last statement, the sum of digits is calculated and displayed on the screen.
randint():
This function accepts two parameters, a and b, as the lowest
and highest numbe
returns a number N' in the inclusive range a,b], which
the endpoints are included in the range. This signifies a<=N<=0, W
function
number between two given numbers. This function isgenerates
a random his
best suited for guess
number applications. The syntax is:
random. randint (a, b)
Here, ais the lower bound and b is the upper bound. In case you input a numberN
then the result generated will be a <= N <= b. Please make sure that the uppet
limit is included in
randint)
Example 8: To generate a number function.
between 0 and 9.
Gimprand1.py
File Edit Format
-C/Users/preeti/A.
Run Options
#
import the random Window Help
module
import candom
print (random.
randint (0,9))
RESTART: C:/Users,preeti/AppData/Local/Prog
rams /Python/
Python36-32/imp randl.py
16 Ln6 Cok 4
Bxample9: Write afunction that fills alist with numbers. (Using randint(0)
andlist py-cNsers/preeti/AppData/Loca/ Programs/Python/Python36-32/tand _Jist1,py(3.6.5)
Run Options Window Help
kdt Fomat
function that fills a list with numbers
A
randint
om random import
(lst, limit
def fill list range (limit num, low, high) :
for i in num) :
lst.append (random. randint (low, high) )
minimum = int (input("Min: "))
maximum = int (input ("Max : "))
n int (input ("Numbers limit :"))
#an empty list
fill list (a, n, minimum, maximum)
print (a) #Prints the newly created list with max and min value inputted
Lns 19 Cok O
statistics Module
The statistics module implements many common statistical formulas for efficient calculations
using Python's various numerical types (int, float, Decimal, and Fraction).
It provides functions for calculating mathematical statistics of numeric (Real-valued)
data. Before using the functions of this module, it is required to be imported first using the
stTheatfollowing
ement- import
popular statistics.
statistical functions are defined in this module:
arithmetic mean of the numbers in
mean(): The
a list.
mean() function calculates the
For example,
>>> import statistics
statistics. mean ([4,6, 7, 8,10, 45])
L3.333333333333334 9.17
returns the middle value of numeric
median() function in a data
median():The value,and if the data set has an even number of lst,
Thisfunctionfindsthecentre
middle items.
values
the twO
itaverages
For example,
>>> import statistics
median([1,2,3, 8,91)
statistics.
>>>
9])
3 .median([1,2,3, 7, 8,
statistics
>>>
5.0 repeated value oft
f the list/sequence passed.
function returnsthe most
o mode():
This
Its syntax is:
statistics .mode (x)
For example,
>>> import statistics
mode ([21,24, 21, 45,56, 67, 21] )
>>> statistics .
21 "blue", "red"))
.mode (("red",
>>> statistics
Mean() to calculate the mean
'red'
user-defined function cal
program using a
Example 10: Write a
in a list.
of floating values stored
Function to calculate mean
below:
The requirements are listed floating point values). elements
parameter (list containing
1. The function should have 1 by total number
of
all the numbers and dividing
2. To calculate mean by adding
Sprogmean,calipy- C/Users/preei/AppData/Local/Programs/Python/Python37-32/prog mean,calipy
the mean
File Edt Format Pun Opions Window Hep calculate
Mean () to
#Program using a user defined function cal
$of floating values stored in a list list
values in
ans of
def cal Mean (1ist1) ; #function to compute mea
total 0
Count 0
tor 1 in 1istl:
total total + 1#Adds each element i to total
count COunt + 1 #Counts the number of elements
mean total/count #nean is calculated
print ("The calculated mean is:",me an)
list1 2.6,3.4,8,5,7.9]
#Function call with 1ist "list1" as an arqument
cal_Mean (list1)
>>>
RZSTART Ci/Users/preeti/AppData
|py
The calculated mean is: 5.6
9.18