Python Unit 4-2 Modules, Package
Python Unit 4-2 Modules, Package
Python Modules
• A module is a file, containing functions, classes and global
variables.
• A module can also include runnable code. Grouping related
code into a module makes it easier to understand and use it by
using simple import statement.
• A module allows you to logically organize your python code.
• The file name is the module name with the suffix .py
appended.
Writing modules
• We don’t require any additional effort or syntax of keyword to
define a module. Just save your code in a python file with .py
extension.
• Modules contain definitions of functions, classes and variables
that can then be utilized in other python programs.
• Example:
• def world(): #function definition
• print(“Hello World”)
• name=“ABC” #variable declaration
• After writing the definition save the file with its name as
welcome.py
Importing modules
• After defining required module, now its time to use it in other
python file or python module.
• To do this we use the import keyword.
• There are 4 ways to import a particular module:
• Simple import statement
• Import with renaming
• Import objects from modules
• Import everything
Simple import statement
• We can import a module using import statement and access
its entities by using the dot operator.
• Syntax:
• import module_name
• This simple import statement will not make the entities of
modules directly accessible. To use the entities of imported
module, we have to use following syntax:
• Module_name . entity_name
• Example:
• Import welcome #importing the modules
• welcome.world() #using its entities
• print(welcome.name)
Import with renaming
• If the name of a module is too large, then we can also import
an entire module under an alternative name.
• We have to use the “as” keyword to rename the module
name.
• To do this, following syntax is used:
• import module_name as alt_name
• Example:
• import welcome as wel
Importing objects from module
• It is possible to import specific attribute/member from a
module without importing the module as a whole.
• To do this we have to use from…..import
• Syntax:
• from module_name import name-1, name-2, name-n
• Example:
• From welcome import name
• print(name)
Import everything
• It is possible to import all the attributes from a module into
current namespace.
• Syntax:
• from module_name import *
Importing multiple modules
• To import multiple modules with a single import statement,
just separate the module names by commas.
• Example:
• Import math, sys, os
Python built-in modules
• Numeric and Mathematical module
• Decimal
• Fractions
• Itertools
• Math
• Operator
• Random
• Functional Programming module
• Lambda expression
• Map function
• Filter function
• Reduce function
Decimal Module
• It is used to do some decimal floating point related tasks. This
module provides correctly rounded floating point arithmetic.
• We have to import decimal
• Functions of Decimal module are as follows
• Decimal(), sqrt()- square root
• exp()- exponential value.
• Ln()- natural logarithm
• log10()- logarithmic value to base 10
• fma(x,y)- (number * x) + y
• import decimal
no=decimal.Decimal(3.14) #gives full presision no.
print("Decimal value:",no)
d1=no.log10()
print("Log Value to the base 10:",d1)
d2=decimal.Decimal(25)
sq=d2.sqrt()
print("Square root: ",sq)
for s in ['1/2','8/4','4/16']:
f=fractions.Fraction(s) #defining function method 2
print(s)
f1=fractions.Fraction(1,2)
f2=fractions.Fraction(3,4)
#arithmetic operations
print(f1,"+",f2,":",f1+f2)
print(f1,"-",f2,":",f1-f2)
print(f1,"*",f2,":",f1*f2)
print(f1,"/",f2,":",f1/f2)
Itertools Module
• This module includes set of functions for working with iterable like
lists , tuples, etc.
• Categorized as:
• Infinite looping :
• These type of iterators produce infinite sequences.
• The methods like cycle, count, repeat comes under this
category in this the methods runs infinitely to stop the
execution we have to provide a terminating condition.
• Terminate on shortest condition:
• These iterators produces the sequences which terminate after
certain iterations.
• The methods like chain, compress, islice, tee comes under this
category. This methods terminate after some condition.
• Methods:
1. Cycle – The Function takes only one argument as input it can be
like list, String, tuple, etc. It repeats the sequence/ elements
provided i.e. elements of list, tuple infinite times. It
restarts printing from the beginning again when all elements
are printed in a cyclic manner.
Example:
import itertools as it
a=it.cycle([1,2,3,4,5])
d=1
for i in a:
# terminating condition, will break when 10 elements are displayed
if d>10: #here 5 elements are present so the set will be printed 2
times
break
else:
print(i)
d +=1
2. Count: count(start, step): This iterator starts printing from
the “start” number and prints infinitely. If steps are mentioned,
the numbers are skipped else step is 1 by default.
Example:
#we have mentioned step-2 so 2nd no. will be printed
a=it.count(0,2)
d=1
for i in a:
# terminating condition, will break when 5 elements are
displayed
if d>5: # here it will print 1st 5 even no.s
break
else:
print(i)
d +=1
3. repeat(val, num): This iterator repeatedly prints the passed
value infinite number of times. If the optional keyword num is
mentioned, then it repeatedly prints num number of times.
Example:
a=it.repeat(10)
d=1
for i in a:
# terminating condition, will break when 5 elements are
displayed
if d>5: # here it will print 10 5 times
break
else:
print(i)
d +=1
• Methods:
• lt(x,y) The lt() method is used to check whether the number x is less
than y or not. It is like x < y operation.
• le(x,y) The le() method is used to check whether the number x is
less than or equal to y or not. It is like x <= y operation.
• eq(x,y) The eq() method is used to check whether the number x and
y are equal or not. It is like x == y operation.
• gt(x,y) The gt() method is used to check whether the number x is
greater than y or not. It is like x > y operation.
• ge(x,y) The ge() method is used to check whether the number x is
greater than or equal to y or not. It is like x >= y operation.
• ne(x,y) The ne() method is used to check whether the number x and
y are not equal. It is like x != y operation.
Random Module
• Python defines a set of functions that are used to generate or
manipulate random numbers through the random
module. Functions in the random module rely on a pseudo-random
number generator function random(), which generates a random
float number between 0.0 and 1.0. These particular type of
functions is used in a lot of games, lotteries, or any application
requiring a random number generation.
• Methods:
• choice() :- choice() is an inbuilt function in the Python programming
language that returns a random item from a list, tuple, or string.
• randrange(beg, end, step):- Returns integer values. The random
module offers a function that can generate random numbers from a
specified range and also allowing rooms for steps to be included,
called randrange().
• random():- This method is used to generate a float random
number less than 1 and greater or equal to 0. i.e. values
between 0 and 1
• Output: 130
Packages
• Packages are a way of structuring many packages and modules
which helps in a well-organized hierarchy of data set, making
the directories and modules easy to access. Just like there are
different drives and folders in an OS to help us store files,
similarly packages help us in storing other sub-packages and
modules, so that it can be used by the user when necessary.
• To tell Python that a particular directory is a package, we
create a file named __init__.py inside it and then it is
considered as a package and we may create other modules
and sub-packages within it. This __init__.py file can be left
blank or can be coded with the initialization code for the
package.
• To create a package in Python, we need to follow these three
simple steps:
• First, we create a directory and give it a package name,
preferably related to its operation.
• Then we put the classes and the required functions in it.
• Finally we create an __init__.py file inside the directory, to let
Python know that the directory is a package.
• module2.py
• class B:
def method3(self):
print("method 3 of class B")
def method4(self):
print("method 4 of class B")
• Create normal python file outside the package folder:
• from pack import module1
from pack import module2
a=module1.A()
a.method1()
a.method2()
b=module2.B()
b.method3()
b.method4()
Using built-in package
• Numpy is the package to use it in our program 1st we have to
install it.
• To install type the following in the terminal section
• pip install numpy
Click here to open terminal
Press enter key it will download numpy
Example for using numpy
• import numpy as np
mat1=np.matrix('1 2 3;4 5 6') #will create matrix
mat2=np.matrix('1 2 3;4 5 6')
•
#perform operations on matrix
sum=np.add(mat1,mat2)
print(sum)
sub=np.subtract(mat1,mat2)
print(sub)
mul=np.multiply(mat1,mat2)
print(mul)
div=np.divide(mat1,mat2)
print(div)
• Example 2:
• import numpy as np
a=np.array(['python','java'])
b=np.array(['programming'])
con=np.char.add(a,b)
print(con)
ran = np.random.randint(10,30,6)
print(ran)