Unit – 4
Python Functions, modules, and
Packages
Prof. Dattatray B. Nanaware
LECTURER IN COMPUTER DEPARTMENT
11/05/2021 Programming with Python By Prof. Nanaware D.B. 1
Learning Outcome
After this session you will be able to :
1. Develop the Python program using standard
functions for the given problem.
2. Develop relevant user defined functions for the given
problem using Python code.
3. Develop Python module for the given problem.
4. Develop Python package for the given problem.
11/05/2021 Programming with Python
. By Prof. Nanaware D.B. 2
Contents :
4.1 Use of Python built — in functions (e.g. type/ data conversion
functions, math functions etc.)
4.2 User defined functions: Function definition, Function calling,
function arguments and parameter passing, Return statement, Scope of
Variables: Global variable and Local Variable.
4.3 Modules: Writing modules, importing modules, importing
objects from modules, Python built — in modules (e.g. Numeric and
mathematical module, Functional Programming Module) Namespace
and Scoping.
4.4 Python Packages: Introduction, Writing Python packages,
Using standard (e.g. math, scipy, Numpy, matplotlib, pandas etc.) and
user defined packages
3
11/05/2021 Programming with Python By Prof. Nanaware D.B.
Type/ data conversion functions :
Sometimes, it‘s necessary to perform conversions
between the built-in types.
To convert between types, we simply use the type
name as a function.
The process of converting the value of one data
type (integer, string, float, etc.) to another data
type is called type conversion.
There are several built-in functions to perform
conversion from one data type to another.
These functions return a new object representing
the converted value
11/05/2021 Programming with Python By Prof. Nanaware D.B. 4
Type/ data conversion functions :
Python has two types of type conversion.
Implicit Type Conversion
Explicit Type Conversion
Implicit Type Conversion:
In Implicit type conversion, Python automatically
converts one data type to another data type. This process
doesn't need any user involvement.
e.g. a = 12
b= 10.23
c=a+b
type(c) ---- > <class,‟float‟>
11/05/2021 Programming with Python By Prof. Nanaware D.B. 5
Type/ data conversion functions :
Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of
an object to required data type. We use the predefined functions
like int(),float(),str() etc
>>> s="10"
>>> num=int(s)
>>> type(num)
<class 'int'>
11/05/2021 Programming with Python By Prof. Nanaware D.B. 6
Type/ data conversion functions :
int(x) Converts x to an integer.
float(x) Converts x to a floating-point number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of
(key,value) tuples.
chr(x) Converts an integer to a character.
ord(x) Converts character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 7
Built in Mathematical functions :
max(x1, x2,...) Return the largest of its arguments
min(x1, x2,...) Return the smallest of its arguments
pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal point.
Abs(value) The absolute value of x
>>> min(10,3,66) 3
>>> max(10,3,66) 66
>>> pow(2,3) 8
>>> round(3.5) 4
>>> round(3.4) 3
>>> round(3.1) 3
>>> round(3.9) 4
>>> abs(2) 2
>>> abs(-2) 2
11/05/2021 Programming with Python By Prof. Nanaware D.B. 8
import math
It is a standard module in Python use to perform mathematical functions
• math.ceil(n) It returns the smallest integer greater than or equal to n.
• math.floor(n) It returns the largest integer less than or equal to n
>>> import math
>>> math.ceil(2.1) 3
>>> math.ceil(2.9) 3
>>> math.floor(2.9) 2
>>> math.floor(2.1) 2
math.fmod(x, y) It returns the remainder when n is divided by y
math.exp(n) It returns exponential value n.
>>> math.fmod(13,5) 3.0
>>> math.exp(2) 7.38
11/05/2021 Programming with Python By Prof. Nanaware D.B. 9
import math
• math.log10(n) It returns the base-10 logarithm of n
• math.pow(n, y) it returns n raised to the power y
• math.sqrt(n) it returns the square root of n
>>> import math
>>> math.log10(2) 0.3010299956639812
>>> math.pow(2,3) 8.0
>>> math.sqrt(4) 2.0
11/05/2021 Programming with Python By Prof. Nanaware D.B. 10
import math
• math.cos(n) it returns the cosine of n
• math.sin(n) it returns the sine of n
• math.tan(n) it returns the tangent of n
• math.pi it is pi value (3.14159...)
• math.factorial(n) It return factorial of n
• math.e mathematical constant e (2.71828...)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 11
Random module:
• Sometimes we want the computer to pick a random
number in a given range or a list.
• To perform this random module is used. This function is
not accessible directly, so we need to import random
module and then we need to call this function using
random static object.
Example:
import random
print(random.random())
print(random.randint(10,20))
Output:
0.8709966760966288
16
12
Operator module:
The operator module supplies functions that are equivalent to python’s operators
Function supplied by operator module are
abs(a) - absolute
add(a,b) - addition
and_(a,b) - logical and
div(a,b) - division
eq(a,b) - equal to
gt(a,b) - greater than
le(a,b) - less than
mod(a,b) - modulus
mul(a,b) - multiplication
or_(a,b) - logical or
not_(a) - logical not
repeat(a,b) - a*b
xor(a,b) - logical xor
13
User Defined functions :
Definition of Function
Syntax/structure of Function
Function calling,
function arguments and parameter passing,
Return statement,
11/05/2021 Programming with Python By Prof. Nanaware D.B. 14
Functions :
1. Function allows us to grouping a number of Statement into
logical block
2. A function is a block of organized and reusable program code
that is used to perform a single, specific related action, and well
defined task.
3. Function enables us to break the large program into number
sub functions which are independent to each other.
4. Once a function is written, it can be reused as and when required.
So, functions are also called reusable code.
5. The use of functions in a program will reduce the length of the
program.
6. Function definition start with ‗ def ‘ keyword.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 15
Syntax of functions
Function begin with Any input parameters or The first statement of a
keyword def followed by arguments should be placed function can be an optional
the function name and within these parentheses. We statement - the
parentheses ( ). can also define parameters documentation string of
inside these parentheses. the function or docstring.
Funname._ _doc_ _
def functionname(parameters):
""" documentation string """
function_Body
return [statement/expression]
The statement return [expression] exits a function,
The code block within every optionally passing back an expression to the caller.
function starts with a colon A return statement with no arguments is the same
(:) and is indented. as return None.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 16
Creating functions without parameter:
#Defining Function
def addition():
"""This function sum the numbers"""
a=10
b=20
c=a+b
print(c)
#Calling Function
addition() # 30
11/05/2021 Programming with Python By Prof. Nanaware D.B. 17
Creating functions with parameter:
#Defining Function
def addition(a,b):
"""This function sum the numbers"""
c=a+b
print(c)
#Calling Function
addition(5,12) # 17
11/05/2021 Programming with Python By Prof. Nanaware D.B. 18
Returning result from functions :
#Defining Function We can return the
def addition(a,b): result or output from
c=a+b the function using a “
return‟ statement in
return c the function body.
When a function
#Calling Function does not return any
res=addition(5,12) result, we need not
print(res) write the return
statement in the body
OUTPUT : # 17 of the function.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 19
Returning multiple values from functions :
#Defining Function We can return the
def addition(a,b): result or output from
c=a+b the function using a “
return‟ statement in
return a,b,c the function body.
#Calling Function When a function
no1,no2,res=addition(5,12) does not return any
print(no1) result, we need not
print(no2) write the return
print(no3) statement in the body
of the function.
OUTPUT : # 17
11/05/2021 Programming with Python By Prof. Nanaware D.B. 20
Display minimum and maximum value from list
#Defining Function
def min_max(l):
print("Elements of List:",l)
x=min(l)
y=max(l)
print("Minimum value=",x)
print("Maximum value=",y)
#Calling Function
l=[10,44,66,77,22,33]
min_max(l)
Output :
Elements of List: [10, 44, 66, 77, 22, 33]
Minimum value= 10
Maximum value= 77
11/05/2021 Programming with Python By Prof. Nanaware D.B. 21
Different Ways of Functions Defination:
The actual arguments used in a function are 4 types:
a) Positional arguments
b) Keyword arguments
c) Default arguments
d) Variable length arguments
11/05/2021 Programming with Python By Prof. Nanaware D.B. 22
Positional arguments/Required arguments :
1. These are the arguments passed to a function in
correct positional order.
2. The number of arguments and their position in the
function definition should match exactly with the
number and position of argument in the function call.
def student(name, rollno):
print("Name=",name)
Output :
print("Roll No=",rollno)
Name= Ram
student("Ram",104) Roll No= 104
#wrong input
Name= 104
student(104,"Ram") Roll No= Ram
11/05/2021 Programming with Python By Prof. Nanaware D.B. 23
Keyword arguments :
• When we call a function with some values, these values
get assigned to the parameter according to their
position.
• Keyword arguments are arguments that identify the
parameters by their names.
def student(name,rollno,mark): OUTPUT
print("Name=",name) Name= 104
print("Roll No=",rollno) Roll No= Ram
print("Marks=",mark) Marks= 65
student(104,"Ram",65) Name= Ram
Roll No= 104
student(rollno=104,name="Ram",mark=65) Marks= 65
11/05/2021 Programming with Python By Prof. Nanaware D.B. 24
Default arguments :
• Python allows user to specify function parameter to
have default values. Default argument assumes a
default values if the value is not provided in function .
def student(name,dept="Computer"): OUTPUT
print("Name=",name)
print("Dept.=",dept)
Name= Om
student(name="Om",dept="Civil") Dept.= Civil
Name= Ram
student(name="Ram") Dept.= Computer
11/05/2021 Programming with Python By Prof. Nanaware D.B. 25
Variable length arguments :
Sometimes, we do not know in advance the number of
arguments that will be passed into a function.
Python allows us to handle this kind of situation through
function calls with number of arguments.
In the function definition we use an asterisk (*)
before the parameter name to denote this is variable
length of parameter.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 26
Variable length arguments :
def student(name,*marks):
print("Name=",name)
print("Marks=",marks)
student("Om",80,90,70,66)
Output :
Name= Om
Marks= (80, 90, 70, 66)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 27
Variable length arguments :
Add(10,20)
Add(10,20,30)
Add(10,20,30,…….)
def add(*args):
sum=0
for i in args:
sum=sum+i
Output :
print("sum is",sum)
sum is 7
add(5,2)
add(5,2,3) sum is 10
add(5,2,3,4,5,6,7) sum is 32
11/05/2021 Programming with Python By Prof. Nanaware D.B. 28
Scope of Variable
All variables in a program may not be accessible at
all locations in that program. This depends on where
the variable is declared. The scope of a variable
determines the portion of the program where you
can access a particular identifier.
Area of the program where the variable is
accessible is called its Scope.
There are two basic scopes of variables in Python-
1. Local Variable 2. Global Variable
11/05/2021 Programming with Python By Prof. Nanaware D.B. 29
Local Variable
def myfunction():
a=10
print("Inside function: ",a)
myfunction()
print("outside function : ",a)
Output :
Inside function : 10
NameError: name 'a' is not defined
11/05/2021 Programming with Python By Prof. Nanaware D.B. 30
Global Variable
a=10
def myfunction():
b=20
print("Inside function",a) #global
print("Inside function",b) #local
myfunction()
print("outside function",a)
print("outside function",b)
Output :
Inside function 10
Inside function 20
outside function 10
NameError: name ‗b' is not defined
11/05/2021 Programming with Python By Prof. Nanaware D.B. 31
Global Variable
When the programmer wants to use the global variable inside a
function, he can use the keyword ― global ― before the variable in
the beginning of the function body
a=10
def myfunction():
global a
a=20
print("Inside function :",a) #global
myfunction()
print("outside function : ",a) #global
OUTPUT :
Inside function : 20
outside function : 20
11/05/2021 Programming with Python By Prof. Nanaware D.B. 32
Namespace in Python:
• Variables are names (identifiers) that map to objects.
• A namespace is a dictionary of variable names (keys)
and their corresponding objects (values).
A Python statement can access variables in a local
namespace and in the global namespace.
If a local and a global variable have the same name, the
local variable shadows the global variable.
• Each function has its own local namespace. Class
methods follow the same scoping rule as ordinary
functions.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 33
The built-in namespace contains
The global namespace contains
the names of all of Python’s built-in
any names defined at the level of
objects. These are available at all
the main program. Python creates
times when Python is running.
the global namespace when the
>>> dir(__builtins__)
main program body starts, and it
remains in existence until the
interpreter terminates.
The Local Namespaces : The
interpreter creates a new
namespace whenever a function
executes. That namespace is local
to the function and remains in
existence until the function
terminates.
34
Functional Programming Module :
Lambda Function
Map function
Filter function
Reduce function
11/05/2021 Programming with Python By Prof. Nanaware D.B. 35
Lambda function:
These functions are called anonymous because they are not
declared in the standard manner by using the def keyword.
Use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just
one value in the form of an expression.
They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because
lambda requires an expression.
Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those in
the global namespace.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 36
Let‟s take a normal function that returns square of given value:
def square(x):
return x*x
The same function can be written as anonymous function as:
lambda x: x*x
The colon (:) represents the beginning of the function that contains an
expression x*x.
The syntax is: Lambda argument_list: expression
f=lambda x:x*x
value = f(5)
print(value)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 37
The syntax is: Lambda argument_list: expression
>>> res=lambda a,b:pow(a,b)
>>> print(res(10,2))
• Lambda function have no name.
• Lambda function can take any number of arguments.
• Lambda function can return just one value in form of an
expression
• Does not have return statement but will return result of
expression.
• Lambda function is one line function hence cannot
contains multiple statements.
• Lambda function cannot access global variable and other
variables.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 38
Map function:
• Map takes a function and a collection of items. It
makes a new, empty collection, runs the function on
each item in the original collection and inserts each
return value into the new collection.
Syntax : r = map(func, seq)
The first argument func is the name of a function and
the second a sequence (e.g. a list) seq. map() applies
the function func to all the elements of the sequence seq.
It returns a new list with the elements changed by func
11/05/2021 Programming with Python By Prof. Nanaware D.B. 39
Syntax r = map(func, seq)
#mapdemo.py OUTPUT :
[2, 5, 5]
l=["Om","Arnav","Swara"]
res=(list(map(len,l)))
print(res)
#sqdemo.py OUTPUT :
def dispsq(x):
return x*x [4, 9, 16, 25]
l=[2,3,4,5]
res=list(map(dispsq,l))
print(res)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 40
filter() function:
Filter takes a function and a collection. It returns a
collection of every item for which the function returned
True.
Syntax : r = filter(func, list)
The first argument func is the name of a function which
returns a Boolean value, i.e. either True or False and the
second a list seq. filter() applies the function func to
every elements of the list. If the function returns True
then element of list will be included in a new list.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 41
#evendemo.py OUTPUT :
def findeven(x):
if x%2==0:
return x
[2, 4, 6, 8, 10]
l=[1,2,3,4,5,6,7,8,9,10]
fres=filter(findeven,l)
print(list(fres)))
#maxdemo.py OUTPUT :
def findmax(x):
if x>75:
return x [82, 95, 77, 99]
l=[82,43,64,95,66,77,99]
fres=filter(findmax,l)
print(list(fres))
11/05/2021 Programming with Python By Prof. Nanaware D.B. 42
reduce() function:
The function reduce(func, seq) continually applies the
function func() to sequence seq. It returns a single value.
If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq)
works like this:
• At first the first two elements of seq will be applied to func, i.e.
func(s1,s2) The list on which reduce() works looks now like
this: [ func(s1, s2), s3, ... , sn ]
• In the next step func will be applied on the previous result and
the third element of the list, i.e. func(func(s1, s2),s3). The list
looks like this now: [ func(func(s1, s2),s3), ... , sn ]
• Continue like this until just one element is left and return this
element as the result of reduce()
11/05/2021 Programming with Python By Prof. Nanaware D.B. 43
#adddemo.py
def addition(x,y):
return x+y
l=[1,2,3,4,5]
fres=reduce(addition,l)
print(fres)
OUTPUT :
15
11/05/2021 Programming with Python By Prof. Nanaware D.B. 44
Modules in Python:
• A python module can be defined as a python program file
which contains a python code including python functions,
class, or variables.
• In other words, we can say that our python code file saved
with the extension (.py) is consider as the module.
• Module has defination of all functions and variables that we
want to use in other programs.
• Modules should be placed in the same directory as that of
program in which it is imported.
• After creating module if we want to access functions and data
of one module in to another python provides ‗ import ‗
keyword.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 45
Steps for Writing and importing Modules
• Writing modules is just like writing a python file that contains
variety of functions definations, classes,and variablesthat can be
reused in other programs.
• Step 1.(Creating) : Create a file as python program and save as
sample.py and write a following code in that file.
#sample.py
def square(num) :
print(“Square=“,num*num)
• Step2. (Importing) : importing modules means to access functions of
one module into another module.
Create a new file in the same directory save as Test.py and write the
code as ..
#Test.py
import sample
11/05/2021 sample.square(10)
Programming with Python By Prof. Nanaware D.B. 46
Importing Modules:
Python provides two ways to import module as.
import statement and from-import statement
# Using import statement : The import statement is used
to import all the functionality of one module into another. We can
import multiple modules with a single import statement
Approach 1 : import modulename
In this way we can access the functions or variables using
dot(.) operator like
modulename.function_name()
modulename.function_name(parameters)
modulename.variable_name
11/05/2021 Programming with Python By Prof. Nanaware D.B. 47
#sample.py
name="OM"
def display():
print("Welcome to python Module")
#TestModule.py
import sample
print("Name=",sample.name)#variable
sample.display() #call function
OUTPUT :
Name= OM
Welcome to python Module
11/05/2021 Programming with Python By Prof. Nanaware D.B. 48
Approach 2 : import module1,module2,. . . .
We can import multiple modules with a single import statement
#module1.py #module2.py
def display(): def show():
print("Module 1") print("Module 2")
#TestModule.py
import module1, module2
module1.display()
Module2.show()
OUTPUT :
Module 1
Module 2
11/05/2021 Programming with Python By Prof. Nanaware D.B. 49
Approach 3 : import with Renaming :
If the module name is too large we can also import entire module
under as alternative name i.e we create alias when import module by
using ― as ‖ keyword
import module as alias_name
#mymodule.py
def display():
print("Module 1")
#TestModule.py
import mymodule1 as m
m.display()
OUTPUT :
Module 1
11/05/2021 Programming with Python By Prof. Nanaware D.B. 50
# Using from- import statement :
• Instead of importing the whole module into the namespace, python
provides the flexibility to import only the specific attributes of a
module.
• This can be done by using from import statement.(ie we can access
only those function and attribute which we need)
• The syntax to use the from import statement is given below.
Approach from modulename import functionname
from modulename import variable
from modulename import fun1,fun2,..
from modulename import*
In this way we can access the functions or variables
directly without using modulename or dot(.) operator .
11/05/2021 Programming with Python By Prof. Nanaware D.B. 51
#module1.py #ModuleTest.py
def addition(a,b): from module2 import square
c=a+b from module1 import*
print("Addition=",c)
def minus(a,b): addition(10,20)
c=a-b
minus(20,3)
print("Subtraction=",c)
square(4)
#module2.py Output :
def square(s):
Addition= 30
res=s*s
print("Area of square=",res) Subtraction= 17
def rect(h,w): Area of square= 16
res=h*w
print("Area of Rectangle=",res)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 52
Package in Python:
• A package is a hierarchical file directory structure
that consists of modules and subpackages and sub-
subpackages.
• Package is collection of python Modules.
• Package is used to organize or grouping the variety of
modules ,files and these group can be done according to
their functionality.
• Every package in python is directory which must have a
special file called _ _init_ _.py. (It will indicate that this
is not an ordinary directory and contains a python
package.)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 53
Steps and Example of creating Package
_ _init_ _.py
MyPack Arith.py
Sample.py
11/05/2021 Programming with Python By Prof. Nanaware D.B. 54
Steps
1. Create a new folder named MyPack under all python files.
2. Create a new empty python file save as _ _init_ _.py
3. Create a new python file save as Arith.py and write a following
code
def sum(a,b):
print("Sum=",(a+b))
def sub(a,b):
print("subtraction=",(a-b))
def pow(a,b):
print("Power(a,b)=",(a**b))
4. Create a new python file save as sample.py and write code as
def display():
print("This is display method")
def show():
print("This is show method")
55
Ways of Import modules, function from package
1. import packagename.modulename
packagename.modulename.fun_name()
2. import packagename.modulename as alias_name
Alias_name.fun_name()
3. from packagename.modulename import *
fun_name()
4. from packagename.modulename import fun_name
fun_name()
11/05/2021 Programming with Python By Prof. Nanaware D.B. 56
Steps
4. Create a new python file TestPack.py and save at location where
all main python source files are stored. And write following code..
import MyPack.sample
MyPack.sample.show()
import MyPack.sample as s
s.display()
from MyPack.Arith import*
sum(20,30)
pow(2,3)
from MyPack.Arith import sub
sub(20,4)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 57
numpy - Package:
1. NumPy stands for numeric python which is a
python package for the computation and
processing of the multidimensional and single
dimensional array.
2. NumPy is a package for scientific computing
which has support for a powerful N-dimensional
array object.
3. NumPy is an N-dimensional array type
called ndarray.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 58
Using NumPy we perform the following operations −
1. Mathematical and logical operations on arrays.
2. Fourier transforms and routines for shape
manipulation.
3. Operations related to linear algebra. NumPy has in-
built functions for linear algebra and random number
generation.
Before you can use NumPy, you need to install it
To install goto script folder path in python at command
prompt
1. pip install numpy or
2. python -m pip install numpy
11/05/2021 Programming with Python By Prof. Nanaware D.B. 59
Creating numpy array:
import numpy as np The output is as follows −
a = np.array([1,2,3])
[1, 2, 3]
print(a)
import numpy as np
a = np.array([ The output is as follows −
[1, 2], [[1, 2]
[3, 4] [3, 4]]
])
Print(a)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 60
arange()
arange() function : It creates an array by using the equally
spaced numbers with given range based on step size
The syntax numpy.arrange(start, stop, step, dtype)
start: The starting of an interval. The default is 0.
stop: represents the value at which the interval ends.
step: The number by which the interval values change.
dtype: the data type of the numpy array items.
import numpy as np
arr = np.arange(0,10,2,float)
print(arr)
Output:
[0. 2. 4. 6. 8.]
11/05/2021 Programming with Python By Prof. Nanaware D.B. 61
Finding the shape and size of the array:
shape : To get the shape ie array dimension
Size : Use to get the size of array ..
import numpy as np Output:
a = np.array([[1,2,3,4,5,6,7]]) Array Size: 7
print("Array Size:",a.size)
print("Shape:",a.shape) Shape: (1, 7)
import numpy as np The output is as follows −
a = np.array([[1,2,3], [[1, 2]
[4,5,6]
[3, 4]
])
a.shape=(3,2) [5,6]]
Print(a)
11/05/2021 Programming with Python By Prof. Nanaware D.B. 62
reshape(row , col)
It is used to reshape the array. It accepts the two parameters
indicating the row and columns of the new shape of the array
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print("printing the original array..")
print(a)
a=a.reshape(2,3)
print("printing the reshaped array..")
print(a)
Output:
printing the original array..
[[1 2]
[3 4]
[5 6]]
printing the reshaped array..
[[1 2 3]
[4 5 6]]
63
NumPy.Zeros
This return new array of specified size filled with zero
numpy.zeros(shape, dtype = float, order = 'C')
It accepts the following parameters.
Shape: The desired shape of the specified array.
dtype: The data type of the array items. default is float.
Order: The default order is the C-style row-major order. It
can be set to F for FORTRAN-style column-major order.
import numpy as np Output:
arr = np.zeros((3,2), dtype = int) [[0 0]
print(arr) [0 0]
[0 0]]
11/05/2021 Programming with Python By Prof. Nanaware D.B. 64
NumPy.ones
This return new array of specified size filled with ones
numpy.ones(shape, dtype = float, order = 'C')
It accepts the following parameters.
Shape: The desired shape of the specified array.
dtype: The data type of the array items. default is float.
Order: The default order is the C-style row-major order. It
can be set to F for FORTRAN-style column-major order.
import numpy as np Output:
arr = np.ones((3,2), dtype = int) [[1 1]
print(arr) [1 1]
[1 1]]
11/05/2021 Programming with Python By Prof. Nanaware D.B. 65
NumPy.full
This return new array of specified size filled with second
parameter
numpy.full(shape, fillwithnumber)
It accepts the following parameters.
Shape: The desired shape of the specified array.
fillwithnumber : fill the shape with given number
import numpy as np Output:
arr = np.full((3,3),2) [[2 2 2]
print(arr) [2 2 2]
[2 2 2]]
11/05/2021 Programming with Python By Prof. Nanaware D.B. 66
NumPy.eye : to create identical matrix
numpy.eye(shape, dtype = float, order = 'C')
It accepts the following parameters.
Shape: The desired shape of the specified array.
dtype: The data type of the array items. default is float.
Order: The default order is the C-style row-major order. It
can be set to F for FORTRAN-style column-major order.
import numpy as np Output:
arr = np.eye((4,4),dtype=int) [[1,0,0,0]
print(arr) [0,1,0,0]
[0,0,1,0]
[0,0,0,1]]
11/05/2021 Programming with Python By Prof. Nanaware D.B. 67
Transpose :
Convert row into column and column into row.
import numpy as np OUTPUT
A= [[1 2]
[3 4]
A = np.array([[1, 2],
[5 6]]
[3, 4],
[5, 6] Trans : [[1 3 5]
]) [2 4 6]]
print("A=",A)
A= [[1 2]
print(“Trans:”A.transpose())
[3 4]
print("A=",A) [5 6]]
print(“after Trans A=",A.T)
after Trans A=
[[1 3 5]
[2 4 6]]
11/05/2021 Programming with Python By Prof. Nanaware D.B. 68
min and max function :
import numpy as np
A = np.array([[1,2,3], [4,5,6], [7,8,9]])
print(“A=”,A)
print("Max=",A.max())
print("min=",A.min())
print("Max Column wise =",A.max(axis=0))
print("Max Row wise = ",A.max(axis=1))
OUTPUT
A= [[1 2 3]
[4 5 6]
[7 8 9]]
Max= 9
min= 1
Max Column wise = [7 8 9]
Max Row wise = [3 6 9]
69
Basic Operation:
OUTPUT
import numpy as np
A= [[1 2]
[3 4]]
B= [[4 3]
A = np.array([[1,2], [3,4]]) [2 1]]
Matrix Addition=
B = np.array([[4,3], [2,1]])
[[5 5]
print("A=",A) [5 5]]
print("B=",B) Matrix Subtraction=
[[-3 -1]
print("Matrix Addition=\n",(A+B))
[ 1 3]]
print("Matrix Subtraction=\n",(A-B))
Array Multiplication=
print("Array Multiplication=\n",(A*B)) [[4 6]
[6 4]]
print("Matrix
Multiplication=\n",(A.dot(B))) Matrix Multiplication=
[[ 8 5]
[20 13]]
70
Linspace() function
It returns equally spaced numbers within the given
range based on sample number
linspace(start,stop,howmany,endpoint=True,dtype=float,retstep=True)
Example
import numpy as np
b=np.linspace(start=1,stop=50,num=10,endpoint=False,dtype=int,retstep=True)
print(b)
array([ 1, 5, 10, 15, 20, 25, 30, 35, 40, 45]), 4.9)
71
To Generate the random number using numpy
Syntax :
numpy.random.randint(low,high,size)
Example :Generate 6 integer random number between 10 to 50
import numpy as np
x=np.random.randint(low=10,high=50,size=6)
print(x)
OUTPUT
[39,36,17,32,24,48
72
pandas - :
• Pandas is a high-level data manipulation tool developed by Wes
Mckinney.
• It is built on the numpy package and its key data structure is
called the dataframe.
• Data frames allow you to store and manipulate tabular data in
rows of observations and columns of variables.
• provides tools for data manipulation: reshaping, merging,
sorting, slicing, aggregation etc.
• allows handling missing data.
• Pandas deals with the following three data structures:
Series
DataFrame
Panel
11/05/2021 Programming with Python By Prof. Nanaware D.B. 73
pandas:
Data Structure Dimensions Description
Series 1 1D labeled homogeneous
array, size-immutable.
Data Frames 2 General 2D labeled, size-
mutable
Panel 3 General 3D labeled, size-
mutable array
11/05/2021 Programming with Python By Prof. Nanaware D.B. 74
Pandas with Series:
Series is a one-dimensional labeled array capable of
holding data of any type (integer, string, float, python
objects, etc.). The axis labels are collectively called index.
1. Create a Series from ndarray
import pandas as pd
import numpy as np output
data = np.array([„Java',„OOP',„Python])
0 Java
s = pd.Series(data)
1 OOP
Print(s) 2 Python
11/05/2021 Programming with Python By Prof. Nanaware D.B. 75
Pandas with Series:
import pandas as pd
import numpy as np
data = np.array([„Java',„OOP',„Python])
s = pd.Series(data,index=[100,101,102])
Print(s)
output
100 Java
101 OOP
102 Python
11/05/2021 Programming with Python By Prof. Nanaware D.B. 76
Pandas DataFrame:
A Data frame is a two-dimensional data structure, i.e., data
is aligned in a tabular fashion in rows and columns
1. Create a DataFrame from Lists
output
import pandas as pd
0
data = [10,20,30,40,50]
0 10
df = pd.DataFrame(data)
1 20
print(df)
2 30
3 40
4 50
11/05/2021 Programming with Python By Prof. Nanaware D.B. 77
DataFrame
import pandas as pd
data = [[„Om',10],[„sai',12],[„Arnav',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)
OUTPUT
Name Age
0 Om 10
1 sai 12
2 Arnav 13
11/05/2021 Programming with Python By Prof. Nanaware D.B. 78
Scipy: pip install Scipy
• SciPy is a library that uses NumPy for more mathematical
functions.
• SciPy uses NumPy arrays as the basic data structure and
come with modules for various commonly used tasks in
scientific programming, including linear algebra,
integration (calculus), ordinary differential equation
solving and signal processing.
• SciPy is organized into subpackage covering different
scientific computing domains.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 79
e.g. using linalg sub package of SciPy
import numpy as np o/p
from scipy import linalg array([[-2.,1.],[1.5,-0.5]])
a=np.array([[1.,2.],[3.,4.]])
linalg.inv(a) # find inverse of array
using linalg sub package of SciPy
import numpy as np
o/p
from scipy import linalg
a=np.array([[8,8,3],[4,5,6],[7,8,9]]) 14.999999
linalg.det(a)
e.g. Using special sub package of SciPy
from scipy.special import cbrt o/p
cb=cbrt([81,64])
array([4.32674871,
print(cb) # find cube root
Matplotlib Package
Matplotlib is one of the most popular Python packages used
for data visualization , It was introduced by John Hunter
in the year 2002.
There are various plots which can be created using python
matplotlib like bar graph, histogram, scatter plot, area plot,
pie plot.
To install matplotlib use following statement goto Script folder
path in command prompt
pip install matplotlib
11/05/2021 Programming with Python By Prof. Nanaware D.B. 82
Linegraph:
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6,7]
y=[1,2,3,4,5,6,7]
plt.plot(x,y)
plt.show()
11/05/2021 Programming with Python By Prof. Nanaware D.B. 83
Bar graph:
import matplotlib.pyplot as plt
sub=["PWP","OS","SWT","OOP","JAVA",]
Res=[88,77,99,74,45]
plt.bar(sub,Res,label="result",color='cyan')
plt.title("Result Analysis")
plt.xlabel("Subjects")
plt.ylabel("Performance")
plt.legend()
plt.grid()
plt.show()
11/05/2021 Programming with Python By Prof. Nanaware D.B. 84
Pie graph:
import matplotlib.pyplot as pt
t=[8,7,5,4]
act=['sleep','work','play','social']
pt.pie(t,labels=act,autopct='%1.2f%%',explode=(0,0,
0,0.2))
pt.show()
11/05/2021 Programming with Python By Prof. Nanaware D.B. 85
import matplotlib.pyplot as plt
Scatter x=[1,2,3,4,5,6,7]
y=[1,2,3,4,5,6,7]
graph plt.scatter(x,y)
plt.show()
11/05/2021 Programming with Python By Prof. Nanaware D.B. 86
scatter graph:
import matplotlib.pyplot as plt
sub2019=["PWP","OS","SWT","OOP","JAVA",]
Res2019=[20,30,40,50,60]
sub2020=["PWP","OS","SWT","OOP","JAVA",]
Res2020=[30,40,50,60,70]
plt.xlabel("Subjects")
plt.ylabel("Performance")
plt.title("Result Analysis Year wise")
plt.scatter(sub2019,Res2019,color='r',label='Result 2019')
plt.scatter(sub2020,Res2020,color='b',label='Result 2020')
plt.legend()
plt.grid(color='y')
plt.show()
87
11/05/2021 Programming with Python By Prof. Nanaware D.B. 88
Summary:
In this unit we discussed about
4.1 Python built — in functions.
4.2 User defined functions.
4.3 Modules.
4.4 Python Packages.
11/05/2021 Programming with Python By Prof. Nanaware D.B. 89
11/05/2021 Programming with Python By Prof. Nanaware D.B. 90