PWP Chapter 4
PWP Chapter 4
Unit No. 4
Python functions, modules
and Packages
by
P. S. Bhandare
Hours: 12
Marks: 14
1|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Syllabus:
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
2|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
The title of chapter Python functions, modules and Packages says that this
chapter includes basic syntax needed for defining the function &
package.
Also, it includes operations performed on using function & Packages
of python programming language.
Outcomes of Chapter:
4a. Use the Python standard functions for the given problem.
4b. Develop relevant user defined functions for the given problem
using Python code.
4c. Write Python module for the given problem
4d. Write Python package for the given problem
3|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
1. The function int(a, base) transforms any data type to an integer. If the type of
data is a string, "Base" defines the base wherein string is.
2. float(): You can turn any data type into a floating-point number with this
function.
4|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
a = "10010"
# # outputting string to int base 2 conversion.
b = int(a,2)
print ("following the conversion to integer base 2: ", end="")
print (r)
# printing a float after converting a string
d = float(a)
print ("After converting to float : ", end="")
print (d)
a = '4'
# printing and converting a character to an integer
b = ord(a)
print ("After converting character into integer : ",end="")
print (b)
# printing integer converting to hexadecimal string
b = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (b)
# printing the integer converting into octal string
b = oct(56)
print ("After converting 56 into octal string : ",end="")
print (b)
x = 'javaTpoint'
# printing string into converting to tuple
y = tuple(x)
print ("After converting the string to a tuple: ",end="")
print (y)
# printing string the converting to set
y = set(x)
print ("After converting the string to a set: ",end="")
print (y)
# printing the string converting to list
y = list(x)
print ("After converting the string to the list: ",end="")
print (y)
5|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
1. Once defined, Python functions can be called multiple times and from any
location in a program.
2. Our Python program can be broken up into numerous, easy-to-follow functions if
it is significant.
3. The ability to return as many outputs as we want using a variety of arguments is
one of Python's most significant achievements.
4. However, Python programs have always incurred overhead when calling
functions.
Syntax:
# An example Python Function
def function_name( parameters ):
# code block
6|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Calling a Function
To call a function, use the function name followed by parenthesis:
E.g.
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments. Arguments are specified after
the function name, inside the parentheses. You can add as many arguments as you want,
just separate them with a comma.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
7|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Recursion
Python also accepts function recursion, which means a defined function can
call itself. Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can loop through
data to reach a result. The developer should be very careful with recursion as it can be
quite easy to slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly recursion
can be a very efficient and mathematically-elegant approach to programming.
e.g.
def fact(n):
if n==0:
return 1;
8|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
else:
return n* fact(n-1)
print(fact(5))
Returning Multiple values:
A function return a single value in the programming languages like C,C++ or java. But in
python function can return multiple values.
E.g.
def arith():
c=10-5
b=20+11
a=20*5
return a,b,c
a1,b1,c1=arith()
print(a1)
print(b1)
print(c1)
myfunc()
myfunc()
print("Python is " + x)
In Python, functions are considered as first class objects. It means we can use functions
as perfect objects. In fact when we create a function, the Python interpreter internally
9|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
creates an object. Since functions are objects, we can pass a function to another function
just like we pass an object (or value) to a function. Also, it is possible to return a
function from another function. This is similar to returning an object (or value) from a
function.
Output:
Hai Krishna
10 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
When a function is defined, it may have some parameters. These parameters are useful
to receive values from outside of the function. They are called formal arguments. When
we call the function, we should pass data or values to the function. These values are
called 'actual arguments'. In the following code, 'a' and 'b' are formal arguments and x
and y are actual arguments.
1. Positional arguments
2. Keyword arguments
3. Default arguments
4. Variable length arguments
Positional Arguments
These are the arguments passed to a function in correct positional order. Here, the
number of arguments and their positions in the function definition should match exactly
with the number and position of the argument in the function call. For example, take a
function definition with two arguments as:
def attach(s1, s2)
This function expects two strings that too in that order only. Let's assume that this
function attaches the two strings as s1+s2 So, while calling this function, we are
supposed to pass only two strings as:
attach(‘New', 'York')
The preceding statement displays the following output: NewYork
Suppose, we passed York' first and then 'New', then the result will be: 'YorkNew'. Also, if
we try to pass more than or less than 2 strings, there will be an error. For example, if we
call the function by passing 3 strings as:
attach('New', 'York', City')
Then there will be an error displayed.
A Python program to understand the positional arguments of a function.
11 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
s 3=s1+s2
print('Total string: '+s3)
attach(‘New', 'York') # positional arguments
Keyword arguments are arguments that identify the parameters by their names. For
example, the definition of a function that displays grocery item and its price can be
written as: def grocery (item, price):
At the time of calling this function, we have to pass two values and we can mention
which value is for what. For example,
grocery (item='Sugar', price=50.75)
Here, we are mentioning a keyword 'item' and its value and then another keyword
'price' and its value. Please observe these keywords are nothing but the parameter
names which receive these values. We can change the order of the arguments as:
grocery (price=88.00, item=’oil')
In this way, even though we change the order of the arguments, there will not be any
problem as the parameter names will guide where to store that value.
Default Arguments
We can mention some default value for the function parameters in the definition. Let's
take the definition of grocery () function as:
def grocery (item, price=40.00):
Here, the first argument is 'item' whose default value is not mentioned. But the second
argument is 'price' and its default value is mentioned to be 40.00. At the time of calling
this function, if we do not pass 'price' value, then the default value of 40.00 is taken. If
we mention the 'price' value, then that mentioned value is utilized. So, a default
argument is an argument that assumes if a value is not provided in the function call for
argument.
A Python program to understand the use of default arguments in a function.
12 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
grocery(item='Sugar')
Output:
Item Price= 50.75
Item Sugar
Price= 40
A keyword variable length argument is an argument that can accept any number of
values provided in the format of keys and values. If we want to use a keyword variable
length argument, we can declare it with '**' before the argument as:
def display(farg, **kwargs):
Here "*kwargs' is called keyword variable argument. This argument internally
represents a dictionary object. A dictionary stores data in the form of key and value
13 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
pairs. It means, when we provide values for **kwargs', we can pass multiple pairs of
values using keywords as:
display(5, rno = 10 )
Modules
So far, we developed several Python programs. These programs can be called 'modules'
if they can be used by other Python programs. So, what is a module? A module is
nothing but a Python program that can be imported into other programs. Since a
module is a Python program, it may contain any stuff like classes, objects, functions,
constants, etc.
In Python, we have several built-in modules like sys, io, time, math, pickle, threading,
etc. Just like these modules, we can also create our own modules and use them
whenever we need them. Let us now develop a module (or Python program) that
contains 2 simple functions add() and sub() to perform addition and subtraction,
respectively.
A Program to create a module with functions. This module contains 2 functions This
module name is arith.py
def add(x, y) :
z=x+y
print('sum of two nos =’,z)
def sub(x, y) :
z=x-y
return z
In the preceding code, observe that the add() function is displaying the result of the sum
of two numbers; whereas, the sub() function is returning the result of subtraction. Save
this code in a file by the name 'arith.py'. Now we can call 'arith.py' as a module, if it can
be used in another program, e.g. ' p * y' For this purpose, we should import the 'arith.py'
module into the 'use.py' program. This can be done by writing import statement inside
the 'use.py' program.
1. import arith
When we write the module name in the import statement as shown in the preceding
code, PVM will add this module name before every Python object in our program, i.e.,
use.py. That means if we have the add() function in our program, PVM will make it
arith.add() internally. Hence, we should call the add() function in our program as
arith.add() or arith.sub().
2. import arith as ar
Here, 4a * r' is another name or alias name for the 'arith' module. When an alias name is
used like this, PVM will add the alias name before the Python object in the program.
Hence, we can call the function using the alias name as ar.add() or ar.sub().
14 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Suppose, in the preceding program, we wrote the import statement as: from arith
import *
Then, we need not write the module name before the functions while calling them.
Since we are importing the 'arith.py' program into the 'use.py' program, we call the
'arith.py' program as a module. Once imported, the contents of the arith module can be
used in the use.py program. In this manner, the arith module can be reused not only in
the use.py program but also in any other program. Thus, modules can be understood as
reusable Python programs. Due to their reusable nature, they make development of the
software easy.
15 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
The Python math module provides various values of various constants like pi,
and tau. We can easily write their values with these constants. The constants
provided by the math module are :
1. Euler’s Number
2. Pi
3. Tau
4. Infinity
5. Not a Number (NaN)
1. Euler’s Number
The math.e constant returns the Euler’s number: 2.71828182846.
Syntax: math.e
Example: This code imports the math module and then prints the value of the
mathematical constant e.
import math
print (math.e)
Output: 2.718281828459045
2. Pi
You all must be familiar with pi. The pi is depicted as either 22/7 or
3.14. math.pi provides a more precise value for the pi.
Syntax : math.pi
e.g.
import math
print (math.pi)
Output: 3.141592653589793
3. tau
Tau is defined as the ratio of the circumference to the radius of a circle.
The math.tau constant returns the value tau: 6.283185307179586.
Syntax: math.tau
import math
print (math.tau)
Output: 6.283185307179586
4. Infinity
Infinity basically means something which is never-ending or boundless from
both directions i.e. negative and positive. It cannot be depicted by a number. The
Python math.inf constant returns of positive infinity. For negative infinity, use -
math.inf.
Syntax: math.inf
Example 1: This code imports the math module and then prints the values of
positive and negative infinity.
import math
print (math.inf)
16 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
print (-math.inf)
Output:
inf
-inf
5. NaN Values
The Python math.nan constant returns a floating-point nan (Not a Number)
value. This value is not a legal number. The nan constant is equivalent to
float(“nan”).
Example: This code imports the math module and then prints the value
of math.nan. math.nan represents Not a Number, which is a special value that is
used to indicate that a mathematical operation is undefined or the result is not a
number.
import math
print (math.nan)
Output: nan
Function
Description
Name
ceil(x) Returns the smallest integral value greater than the number
copysign(x, y) Returns the number with the value of ‘x’ but with the sign of ‘y’
fabs(x) Returns the absolute value of the number
factorial(x) Returns the factorial of the number
floor(x) Returns the greatest integral value smaller than the number
gcd(x, y) Compute the greatest common divisor of 2 numbers
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
Returns the precise floating-point value of sum of elements in an
fsum(iterable)
iterable
isfinite(x) Check whether the value is neither infinity not Nan
isinf(x) Check whether the value is infinity or not
isnan(x) Returns true if the number is “nan” else returns false
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns the value of e raised to the power x(e**x)
expm1(x) Returns the value of e raised to the power a (x-1)
17 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Function
Description
Name
log(x[, b]) Returns the logarithmic value of a with base b
log1p(x) Returns the natural logarithmic value of 1+x
log2(x) Computes value of log a with base 2
log10(x) Computes value of log a with base 10
pow(x, y) Compute value of x raised to the power y (x**y)
sqrt(x) Returns the square root of the number
acos(x) Returns the arc cosine of value passed as argument
asin(x) Returns the arc sine of value passed as argument
atan(x) Returns the arc tangent of value passed as argument
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of value passed as argument
hypot(x, y) Returns the hypotenuse of the values passed in arguments
sin(x) Returns the sine of value passed as argument
tan(x) Returns the tangent of the value passed as argument
degrees(x) Convert argument value from radians to degrees
radians(x) Convert argument value from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of value passed as argument
asinh(x) Returns the inverse hyperbolic sine of value passed as argument
atanh(x) Returns the inverse hyperbolic tangent of value passed as argument
cosh(x) Returns the hyperbolic cosine of value passed as argument
sinh(x) Returns the hyperbolic sine of value passed as argument
tanh(x) Returns the hyperbolic tangent of value passed as argument
erf(x) Returns the error function at x
erfc(x) Returns the complementary error function at x
gamma(x) Return the gamma function of the argument
lgamma(x) Return the natural log of the absolute value of the gamma function
Packages
A package is a folder or directory that contains some modules. How PVM distinguishes a
normal folder from a package folder is the question. To differentiate the package folder,
we need to create an empty file by the name 'init_.py' inside the package folder.
following figure shows a package 'mypack' with a module 'arith.py' in it. The The
module contains functions add() and sub() and we have to use them in another program
'use.py' which is outside of the package.
18 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
First of all, we should create a folder by the name 'mypack'. For this purpose, right click
the mouse → New Folder. Then it will create a new folder by the name 'New folder'.
Rename it as 'mypack'. The next step is to create '__init__.py' file as an empty file inside
'mypack' folder. First, go to the mypack folder by double clicking on it. Then right click
the mouse → New → Text Document. This will open a Notepad file by the name 'New
Text Document.txt'. Double click on this file to open it. Then File → Save As Type the file
name in double quotes as
“__init__.py”.
Now we can see a new file by the name __init__.py' with 0 KB size created in the mypack
folder. Store the 'arith.py' program into this mypack folder. Now mypack is treated as a
package with arith.py as a module.
Come out of mypack. We can use this mypack package in any program like 'use.py' that
is stored out of the package. We can write the use.py program to import the module
from the mypack package.
A Program showing how to use a module belonging to a package.
import mypack.arith
mypack.arith.add(10,22)
result=mypack.arith.sub(10, 22)
print('Result of subtraction= result)
Output:
Sum of two nos= 32
Result of subtraction= -12
The following are the other ways of writing the import statement:
1. import mypack.arith as ar
Then refer to the functions as: ar.add() or ar.sub()
2. from mypack.arith import
3. from mypack.arith import add, sub
In the above two cases, we can directly call the functions as add() or sub().
19 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Libraries
We can extend the concept of packages to form libraries. A group of packages is called a
'software library', often simply called a 'library'. A library contains several packages and
each package contains 1 or more modules. Each module in turn contains several useful
classes and functions. When a project is going on, as part of the project, several
programmers may create packages and the related packages form the library.
Nowadays, top companies are sharing such libraries with other companies freely; the
other companies can import and use those libraries in their own projects. Thus, sharing
of knowledge is taking place between various companies.
Program Code 1:
Now we gave an example of a lambda function that adds 4 to the input number is shown
below.
# Code to demonstrate how we can use a lambda function for adding 4 numbers
add = lambda num: num + 4
print( add(6) )
Output: 10
Here we explain the above code. The lambda function is "lambda num: num+4" in the
given programme. The parameter is num, and the computed and returned equation is
num * 4.
There is no label for this function. It generates a function object associated with the
"add" identifier. We can now refer to it as a standard function. The lambda statement,
"lambda num: num+4", is written using the add function, and the code is given below:
Program Code 2:
20 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Program Code 3:
Now we gave an example of a lambda function that multiply 2 numbers and return one
result. The code is shown below -
a = lambda x, y : (x * y)
print(a(4, 5))
Output: 20
Program Code 4:
a = lambda x, y, z : (x + y + z)
print(a(4, 5, 5))
Output: 14
Python Namespaces
Python Namespaces are collections of different objects that are associated with unique
names whose lifespan depends on the scope of a variable. The scope is a region from
where we can access a particular object. There are three levels of scopes: built-in
(outermost), global, and local. We can only access an object if its scope allows us to do
so.
A namespace is a system that has a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form
of a Python dictionary.
21 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
# namespace
var3 = 7
Understanding Scope
In programming, the scope of a name defines the area of a program in which you can
unambiguously access that name, such as variables, functions, objects, and so on. A
name will only be visible to and accessible by the code in its scope. Several
programming languages take advantage of scope for avoiding name collisions and
unpredictable behaviors. Most commonly, you’ll distinguish two general scopes:
Global scope: The names that you define in this scope are available to all your code.
Local scope: The names that you define in this scope are only available or visible to the
code within the scope.
Using the LEGB Rule for Python Scope
Python resolves names using the so-called LEGB rule, which is named after the Python
scope for names. The letters in LEGB stand for Local, Enclosing, Global, and Built-in.
Here’s a quick overview of what these terms mean:
Local (or function) scope is the code block or body of any Python function
or lambda expression. This Python scope contains the names that you define inside the
function. These names will only be visible from the code of the function. It’s created at
function call, not at function definition, so you’ll have as many different local scopes as
function calls. This is true even if you call the same function multiple times,
or recursively. Each call will result in a new local scope being created.
Enclosing (or nonlocal) scope is a special scope that only exists for nested functions. If
the local scope is an inner or nested function, then the enclosing scope is the scope of
the outer or enclosing function. This scope contains the names that you define in the
enclosing function. The names in the enclosing scope are visible from the code of the
inner and enclosing functions.
Global (or module) scope is the top-most scope in a Python program, script, or
module. This Python scope contains all of the names that you define at the top level of a
program or a module. Names in this Python scope are visible from everywhere in your
code.
Built-in scope is a special Python scope that’s created or loaded whenever you run a
script or open an interactive session. This scope contains names such as keywords,
functions, exceptions, and other attributes that are built into Python. Names in this
Python scope are also available from everywhere in your code. It’s automatically loaded
by Python when you run a program or script.
NumPy
NumPy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object and tools for working with these arrays. It is the
fundamental package for scientific computing with Python. It is open-source software.
Features of NumPy
NumPy has various features including these important ones:
1. A powerful N-dimensional array object
2. Sophisticated (broadcasting) functions
3. Tools for integrating C/C++ and Fortran code
4. Useful linear algebra, Fourier transform, and random number capabilities
Install Python NumPy
Numpy can be installed for Mac and Linux users via the following pip command:
22 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
23 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
24 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Let's say we want to create a 3-D NumPy array consisting of two "slices" where each
slice has 3 rows and 4 columns.
Here's how we create our desired 3-D array,
import numpy as np
print(array1)
Run Code
Output
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
25 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
# Output: 2
import numpy as np
# Example matrices
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
for r in result:
print(r)
Pandas
26 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Pandas is a Python library used for working with data sets.It has functions for analyzing,
cleaning, exploring, and manipulating data. The name "Pandas" has a reference to both
"Panel Data", and "Python Data Analysis" and was created by Wes McKinney in 2008.
Import Pandas
Once Pandas is installed, import it in your applications by adding the import keyword:
import pandas
Now Pandas is imported and ready to use.
ExampleGet your own Python Server
import pandas
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pandas.DataFrame(mydataset)
print(myvar)
o/p:
cars passings
0 BMW 3
1 Volvo 7
2 Ford 2
import pandas as pd
mydataset = { 'cars': ["BMW", "Volvo", "Ford"], 'passings': [3, 7, 2]}
myvar = pd.DataFrame(mydataset)
print(myvar)
import pandas as pd
calories = {"day1": 420, "day2": 380, "day3": 390}
27 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
myvar = pd.Series(calories)
print(myvar)
Matplotlib
Matplotlib is a Python library which is defined as a multi-platform data visualization
library built on Numpy array. It can be used in python scripts, shell, web application,
and other graphical user interface toolkit.
The John D. Hunter originally conceived the matplotlib in 2002. It has an active
development community and is distributed under a BSD-style license. Its first version
was released in 2003, and the latest version 3.1.1 is released on 1 July 2019.
Matplotlib 2.0.x supports Python versions 2.7 to 3.6 till 23 June 2007. Python3 support
started with Matplotlib 1.2. Matplotlib 1.4 is the last version that supports Python 2.6.
There are various toolkits available that are used to enhance the functionality of
the matplotlib. Some of these tools are downloaded separately, others can be shifted
with the matplotlib source code but have external dependencies.
Bashmap: It is a map plotting toolkit with several map projections, coastlines, and
political boundaries.
Cartopy: It is a mapping library consisting of object-oriented map projection
definitions, and arbitrary point, line, polygon, and image transformation abilities.
Excel tools: Matplotlib provides the facility to utilities for exchanging data with
Microsoft Excel.
Mplot3d: It is used for 3D plots.
Natgrid: It is an interface to the Natgrid library for irregular gridding of the spaced data.
Matplotlib Architecture
There are three different layers in the architecture of the matplotlib which are the
following:
Backend Layer
Artist layer
Scripting layer
Backend layer
The backend layer is the bottom layer of the figure, which consists of the
implementation of the various functions that are necessary for plotting. There are three
essential classes from the backend layer FigureCanvas(The surface on which the figure
will be drawn), Renderer(The class that takes care of the drawing on the surface),
and Event(It handle the mouse and keyboard events).
Artist Layer
The artist layer is the second layer in the architecture. It is responsible for the various
plotting functions, like axis, which coordinates on how to use the renderer on the figure
canvas.
Scripting layer
The scripting layer is the topmost layer on which most of our code will run. The
methods in the scripting layer, almost automatically take care of the other layers, and all
we need to care about is the current state (figure & subplot).
The General Concept of Matplotlib
A Matplotlib figure can be categorized into various parts as below:
28 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
Figure: It is a whole figure which may hold one or more axes (plots). We can think of a
Figure as a canvas that holds plots.
Axes: A Figure can contain several Axes. It consists of two or three (in the case of 3D)
Axis objects. Each Axes is comprised of a title, an x-label, and a y-label.
Axis: Axises are the number of line like objects and responsible for generating the graph
limits.
Artist: An artist is the all which we see on the graph like Text objects, Line2D objects,
and collection objects. Most Artists are tied to Axes.
Install Matplotlib with pip
The python package manager pip is also used to install matplotlib. Open the command
prompt window, and type the following command:
29 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
1. Line graph
The line graph is one of charts which shows information as a series of the line. The
graph is plotted by the plot() function. The line graph is simple to plot; let's consider the
following example:
from matplotlib import pyplot as plt
x = [4,8,9]
y = [10,12,15]
plt.plot(x,y)
plt.title("Line graph")
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
2. Bar graphs
Bar graphs are one of the most common types of graphs and are used to show data
associated with the categorical variables. Matplotlib provides a bar() to make bar
graphs which accepts arguments such as: categorical variables, their value and color.
30 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
plot(x-axis value, y-axis- It is used to plot a simple line graph with x-axis value against
values) the y-axis values. show() It is used to display the graph.
title("string") It is used to set the title of the plotted graph as specified by the
string.
xlabel("string") It is used to set the label for the x-axis as specified by the
string.
ylabel("string") It is used to set the label for y-axis as specified by the string.
31 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
subplots(nrows,ncols,figsize) It provides the simple way to create subplot, in a single call and
returns a tuple of a figure and number of axes.
set_title("string") It is an axes level method which is used to set the title of the
subplots.
xtricks(index, categorical It is used to set or get the current tick locations labels of the x-
variables) axis.
xlim(start value, end value) It is used to set the limit of values of the x-axis.
ylim(start value, end value) It is used to set the limit of values of the y-axis.
scatter(x-axis values, y-axis It is used to plots a scatter plot with x-axis value against the y-
values) axis values.
set_xlabel("string") It is an axes level method which is used to set the x-label of the
plot specified as a string.
32 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
plot3D(x-axis values, y-axis It is used to plots a three-dimension line graph with x- axis
values) values against y-axis values.
SciPy
The SciPy is an open-source scientific library of Python that is distributed under a BSD
license. It is used to solve the complex scientific and mathematical problems. It is built
on top of the Numpy extension, which means if we import the SciPy, there is no need to
import Numpy. The Scipy is pronounced as Sigh pi, and it depends on the Numpy,
including the appropriate and fast N-dimension array manipulation.
SciPy Installation
We will learn about the core functionality of SciPy. Before working with SciPy, it should
be installed in the system.
We can install the SciPy library by using pip command; run the following command in
the terminal:
We can also install SciPy packages by using Anaconda. First, we need to download the
Anaconda navigator and then open the anaconda prompt type the following command:
33 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
SciPy Constant
The scipy.constant package is available with a wide range of constants, which is used
extensively in the scientific field. There are various physical, mathematical constants
and units that we can import the required constants and use them as per needed.
1. pi pi
Consider the following example of scipy.constant. Here we compare the 'pi' value by
importing different modules.
Output:
The above code will give the following output. As we can observe that both values are
same.
34 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
5. E Elementry charge
9. K Boltzmann constant
1. Mass
35 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
2. Time
3. Length
4. Pressure
36 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
5. Area
6. Speed
SciPy Integrate
Sometimes a function is very complicated to integrate or cannot be integrated
analytically; then, it can be solved by the numerical integration method. SciPy provides
some routines for performing numerical integration. The scipy.integrate library
contains most of these functions.
o Single Integrals
Numerical integrate is sometimes called quadrature. The Quad function is essential for
SciPy's integration functions. The syntax of the quad() function is the following:
1. scipy.integrate.quad(f,a,b),
Parameters:
b- It is a upper limit.
Let's consider the Gaussian function, integrated over a range from a to b. We define the
functionf(x)= e-x2, this can be done using a lambda expression and apply the quad
method on the given function.
1. import scipy.integrate
37 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)
38 | P a g e
Prashant S. Bhandare