Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Python Unit 4-2 Modules, Package

Python module related information. Can be used in last semester of diploma. And in third semester of b.tech.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Unit 4-2 Modules, Package

Python module related information. Can be used in last semester of diploma. And in third semester of b.tech.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Python Modules

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)

d3=no.fma(10,20) #fma(x,y)- (number * x) + y


print(d3)
Fraction module
• We have to import fractions module
• We can perform arithmetic operations on the fraction values.
• We get the output in fraction format only.
import fractions
for n,d in [(1,2),(2,3),(3,6)]:
f=fractions.Fraction(n,d) #defining fraction
print(f)

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

If we will mention a=i.repeat(10,3) then 10 will be printed 3


times.
4. chain(iter1, iter2..): This function is used to print all the
values in iterable targets one after another mentioned in its
arguments.
Example:
a=[1,2,3]
b=[4,5,6,7]
a=it.chain(a,b) #returns combination of list a and b
for i in a:
print(i)
5. compress(iter, selector): This iterator selectively picks the
values to print from the passed container according to the
Boolean list value passed as other arguments. The arguments
corresponding to Boolean true are printed else all are skipped.
Example:
a=[1,2,3,4,5]
s=[1,0,0,1,1]
b=it.compress(a,s) #only prints value with 1 present in s
for i in b:
print(i)
6. islice(iterable, start, stop, step): This iterator selectively prints
the values mentioned in its iterable container passed as
argument. This iterator takes 4 arguments, iterable container,
starting pos., ending position and step.
Example:
a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
#islice(list_name,start_value,how elements from list,steps)
b=it.islice(a,0,10,3)
for i in b:
print(i)
#will print every 3rd element from list a but will consider only
10 elements
7. tee(iterator, count):- This iterator splits the container into a
number of iterators mentioned in the argument.
Example:
a=[1,2,3,4,5,6,7]
at=iter(a)
b=it.tee(at,3) #will print the enitre list 3 times
for i in b:
print(list(i))
Math module
• Some of the most popular mathematical functions are defined
in the math module. These include trigonometric functions,
representation functions, logarithmic functions, angle
conversion functions, etc.
• In addition, two mathematical constants are also defined in
this module.
• Pi is a well-known mathematical constant, which is defined as the
ratio of the circumference to the diameter of a circle and its value
is 3.141592653589793.
• Another well-known mathematical constant defined in the math
module is e. It is called Euler's number and it is a base of the
natural logarithm. Its value is 2.718281828459045.
• Methods of math module
• Sqrt( ) method returns the square root of a given number.
• Floor( ) function returns the largest integer less than or equal
to the given number.
• Ceil( ) function approximates the given number to the smallest
integer, greater than or equal to the given floating point
number.
• Pow( ) method receives two float arguments, raises the first to
the second and returns the result. In other words, pow(4,4) is
equivalent to 4**4.
• math.exp() method returns a float number after raising e to
the power of the given number. In other
words, exp(x) gives e**x.
Example
• import math
print("Sqrt:",math.sqrt(25))
print("Ceil:",math.ceil(3.6))
print("floor:",math.floor(3.6))
print("pow:",math.pow(2,4))
print("exp",math.exp(2))
Operator module
• In Python there are some additional standard library methods for
mathematical operations, like arithmetic, logical, operations.
Operator module is used for this
• Methods: Arithmetic Operations
• add(x,y) The add() method is used to add two numbers x and y. It
performs simple addition. It is similar to the x + y operation.
• sub(x,y) The sub() method is used to subtract y from x. It is similar
to the x - y operation.
• mul(x,y) The mul() method is used to multiply two numbers x and y.
It is similar to the x * y operation.
• floordiv(x,y) The floordiv() method is used to find the quotient of
x/y. It is similar to the x // y operation.
• mod(x,y) The mod() method is used to get the remainder of x/y. It is
similar to the x % y operation.
• Relational Operations
• The operator module also contains the relational operators like <,
<=, >, >=, ==, !=.

• 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

• shuffle():- It is used to shuffle a sequence (list). Shuffling


means changing the position of the elements of the sequence.
Here, the shuffling operation is in place.

• uniform(a, b):- This function is used to generate a floating


point random number between the numbers mentioned in
its arguments. It takes two arguments, lower limit(included
in generation) and upper limit(not included in generation).

• Randint():- method returns a random integer between the


specified integers.
Example
• import random, numpy as np
#randrange( )
print(random.randrange(100,500)) #prints random no. between 100 to 500
print(random.randrange(10)) #prints random no. between 0 to 10
#random()
print(random.random()) #no. between 0 and 1
#randint()
print(np.random.randint(1,6,3)) #3 random nos. between 1 to 6
#choice( )
print(random.choice("Python")) #random letter from "Python"
list1=[10,1,2,3,50,68,94,100]
print(random.choice(list1)) #random element from list1
#uniform()
print(random.uniform(1,10)) #random float no between 1 to 10
#shuffle()
list2=[10,20,30,40,50,60,70,80,90,100]
random.shuffle(list2) #shuffles the order of elements in list2
print(list2)
Functional Programming
module
• Lambda expression
• Map function
• Filter function
• Reduce function
Lambda expression
• In Python, an anonymous function means that a function is without
a name. As we already know that the def keyword is used to define a
normal function in Python. Similarly, the lambda keyword is used to
define an anonymous function in Python.
• Syntax: lambda arguments : expression
• Example: lambda_cube = lambda y: y*y*y
• print(lambda_cube)
• Lambda definition does not include a “return” statement, it always
contains an expression that is returned. We can also put a lambda
definition anywhere a function is expected, and we don’t have to
assign it to a variable at all. This is the simplicity of lambda
functions.
• Example 2:
• # showing difference between def() and lambda().
• def cube(y):
• return y*y*y

• lambda_cube = lambda y: y*y*y

• # using the normally defined function
• print(cube(5))

• # using the lambda function
• print(lambda_cube(5))
Map function
• map() function returns a map object(which is an iterator) of
the results after applying the given function to each item of a
given iterable (list, tuple etc.)
• Syntax :
• map(fun, iter)
• Parameters :
• fun : It is a function to which map passes each element of
given iterable.
iter : It is a iterable which is to be mapped.
• Returns :
• Returns a list of the results after applying the given function to
each item of a given iterable (list, tuple etc.)
Example
• def sq(n):
return (n*n)
list1=[1,2,3,4,5]
res=map(sq,list1)
print(list(res))
Filter function
• The filter() method filters the given sequence with the help of
a function that tests each element in the sequence to be true
or not.
• syntax:
• filter(function, sequence)
• Parameters:
• function: function that tests if each element of a sequence
true or not.
• sequence: sequence which needs to be filtered, it can be
sets, lists, tuples, or containers of any iterators.
• Returns: returns an iterator that is already filtered.
Example:
• def odd(num):
if(num%2==1):
return True
list2=[1,5,4,2,6,8,9,11,25,12]
re=list(filter(odd,list2))
print(re)

• Finds odd no.s from the list provided.


Reduce Function
• The reduce(fun,seq) function is used to apply a particular
function passed in its argument to all of the list
elements mentioned in the sequence passed along.This
function is defined in “functools” module.
• Example:
• from functools import reduce
list3=[47,11,42,13,17]
res=reduce(lambda x,y : x+y, list3) #addition of all elements
in list3
print(res)

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

• Example of user defined package


Click on python package and name it as pack
It will create package with name pack and __init__.py by deafult

Create modules of your choice with any name here the


names are module 1 and module 2
• module1.py
• class A:
def method1(self):
print("method 1 of class A")
def method2(self):
print("method 2 of class A")

• 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)

You might also like