0% found this document useful (0 votes)
150 views

PWP Chapter 4

The document discusses Python functions, modules, and packages. It provides an overview of the chapter syllabus which covers built-in and user defined functions, modules, importing modules and objects, and Python packages. It also gives examples of type conversion, built-in math functions, and defining user functions in Python.

Uploaded by

Sanket Badave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views

PWP Chapter 4

The document discusses Python functions, modules, and packages. It provides an overview of the chapter syllabus which covers built-in and user defined functions, modules, importing modules and objects, and Python packages. It also gives examples of type conversion, built-in math functions, and defining user functions in Python.

Uploaded by

Sanket Badave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

Name of Staff: Mr. P. S. Bhandare


Name of Subject: Programming with Python
Subject code: 22616
Class: TYCO
Department: Computer Engineering

Unit No. 4
Python functions, modules
and Packages
by
P. S. Bhandare

College of Engineering (Polytechnic),


Pandharpur

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)

About Title of Chapter:

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

About Central Idea of Chapter:

 The central idea of chapter is that by studying this chapter student


will learn about defining the function module & package & their use
in python programming.

About Importance of Chapter:

 This chapter is important because this will introduce basics of


function definition, basic of module with its operations. Also study of
important different packages is provided in this chapter.

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)

Type Conversion in Python:


Converting one type of data into another type is called as type conversion.
In Python, there are two kinds of type conversion, these are -
 Explicit Type Conversion-The programmer must perform this task manually.
 Implicit Type Conversion-By the Python program automatically.

Implicit Type Conversion


Implicit character data conversion is used in Python when a data type conversion
occurs, whether during compilation or runtime. We do not need to manually change the
file format into some other data type because Python performs the implicit character
data conversion. Throughout the tutorial, we have seen numerous examples of this type
of data type conversion. Without user input, the Programming language automatically
changes one data type to another in an implicit shift of data types.
e.g.
a = 15
print("Data type of a:",type(a))
b = 7.6
print("Data type of b:",type(b))
c=a+b
print("The value of c:", c)
print("Data type of c:",type(c))
d = "Priya"
print("Data type of d:",type(d))
Output: Data type of a: <class 'int'>
Data type of b: <class 'float'>
The value of c: 22.6
Data type of c: <class 'float'>
Data type of d: <class 'str'>

Explicit Type Conversion:


Let us say we want to change a number from a higher data type to a lower data type.
Implicit type conversion is ineffective in this situation, as we observed in the previous
section. Explicit type conversion, commonly referred to as type casting, now steps in to
save the day. Using built-in Language functions like str() to convert to string form and
int() to convert to integer type, a programmer can explicitly change the data form of an
object by changing it manually.
The user can explicitly alter the data type in Python's Explicit Type Conversion
according to their needs. Since we are compelled to change an expression into a certain
data type when doing express type conversion, there is chance of data loss. Here are
several examples of explicit type conversion.

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)

3. The ord() method turns a character into an integer.


4. The hex() method turns an integer into a hexadecimal string.
5. The oct() method turns an integer into an octal string.
e.g.

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)

6. The tuple() method is used to transform data into a tuple.


7. The set() function, which converts a type to a set, returns the set.
8. The list() function transforms any data type into a list type.

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)

Built-in Math Functions


1. abs() – returns the absolute value of a number
2. pow() – raises a number to a specified power
3. round() – rounds a number to a specified number of decimal places
4. max() – returns the largest value in a list or tuple
5. min() – returns the smallest value in a list or tuple
6. divmod() - returns the quotient and remainder when one number is divided by
another
7. sum() - returns the sum of all the elements in a list or tuple
8. round() - rounds a number to the nearest integer
e.g.
print(abs(-10)) # Output: 10
print(pow(2, 3)) # Output: 8
print(round(3.14159, 2)) # Output: 3.14
print(max(2, 5, 8, 1)) # Output: 8
print(min(2, 5, 8, 1)) # Output: 1
print(divmod(10, 3)) # Output: (3, 1)
my_list = [1, 2, 3, 4, 5]
print(sum(my_list)) # Output: 15
print(round(3.7)) # Output: 4

User defined functions:


A collection of related assertions that carry out a mathematical, analytical, or evaluative
operation is known as a function. An assortment of proclamations called Python
Capabilities returns the specific errand. Python functions are necessary for
intermediate-level programming and are easy to define. Function names meet the same
standards as variable names do. The objective is to define a function and group-specific
frequently performed actions. Instead of repeatedly creating the same code block for
various input variables, we can call the function and reuse the code it contains with
different variables.

Advantages of Python Functions:

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

1. The start of a capability header is shown by a catchphrase called def.

6|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

2. function_name is the function's name, which we can use to distinguish it from


other functions. We will utilize this name to call the capability later in the
program. Name functions in Python must adhere to the same guidelines as
naming variables.
3. Using parameters, we provide the defined function with arguments.
Notwithstanding, they are discretionary.
4. A colon (:) marks the function header's end.
5. We can utilize a documentation string called docstring in the short structure to
make sense of the reason for the capability.
6. Several valid Python statements make up the function's body. The entire code
block's indentation depth-typically four spaces-must be the same.
7. A return expression can get a value from a defined function.
Creating a Function
In Python a function is defined using the def keyword:
E.g.
def my_function():
print("Hello from a function")

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

Arbitrary Arguments: (*args)


If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly:
E.g.
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
E.g.

7|Page
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

def my_function(child3, child2, child1):


print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments: (**kwargs)


If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly:
E.g.
If the number of keyword arguments is unknown, add a double ** before the parameter
name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
E.g.
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function. if you send a List as
an argument, it will still be a List when it reaches the function:
E.g.
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

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)

Local and Global Variables


When we declare a variable inside a function, it becomes a local variable. A local
variable is a variable whose scope is limited only to that function where it is created.
That means the local variable value is available only in that function and not outside of
that function. In the following example, the variable 'a' is declared inside myfunction()
and hence it is available inside that function. Once we come out of the function, the
variable 'a' is removed from memory and it is not available. Consider the following code:
e.g.
x = "awesome" #global declaration
def myfunc():
y=”good” #local declaration
print("Python is " + x+” &”+y)

myfunc()

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can
only be used inside that function. To create a global variable inside a function, you can
use the global keyword.
e.g.
def myfunc():
global x
x = "fantastic"

myfunc()
print("Python is " + x)

Functions are First Class Objects

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.

The following possibilities are noteworthy:

1. It is possible to assign a function to a variable.


2. It is possible to define one function inside another function.
3. It is possible to pass a function as parameter to another function.
4. It is possible that a function can return another function.

To understand these points, we will take a few simple programs

A Python program to see how to assign a function to a variable.

# assign a function to a variable


def display(str):
return 'Hai '+str
#assign function to variable x
x=display("Krishna")
print(x)

Output:
Hai Krishna

A Python program to know how to define a function inside another function.

# define a function inside another function

def display(str): def message():


return “How are u? “
result = message()+str
return result
#call display() function
print(display("Krishna"))

Output: How are U? Krishna

We are trying to pass message() function as a parameter or argument to display()


function. Since display() function has to receive another function as its parameter, it
should be defined with another function 'fun' as parameter as:

A Python program to know how to pass a function as parameter to another function.

#functions can be passed as parameters to other functions


def display(fun):
return 'Hai’ + fun
def message():

10 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

return ‘How are u?'


#call display() function and pass message() function
print(display(message()))

Output: Hai How are u?


Formal and Actual Arguments

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.

def sum(a, b): # a, b are formal arguments


c=a+b
print (c)
# call the function
x=10; y=15 sum(x, y) # x, y are actual arguments

The actual arguments used in a function call are of 4 types:

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.

# positional arguments demo


def attach (s1, s2):

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

Output: Total string: NewYork


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

A Python program to understand the keyword arguments of a function.

def grocery(items, price)


print(“Item=%s”, %item)
print(“prize=%0.2f”, %price)

grocery (item=Sugar, price=50.75)


Output:
Price= 50.7
Item - oil
Price= 88C

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.

def grocery (item, price-40.00):


print('Item= %s' %item)
print('Price=%.2f ' %price)
grocery item Sugar, price= 50.75 )

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

Variable Length Arguments


Sometimes, the programmer does not know how many values a function may receive. In
that case, the programmer cannot decide how many arguments to be given in the
function definition. For example, if the programmer is writing a function to add two
numbers, he can write:
add(a, b)
But, the user who is using this function may want to use this function to find sum of
three numbers. In that case, there is a chance that the user may provide 3 arguments to
this function as:
add(10, 15, 20)
Then the add() function will fail and error will be displayed. If the programmer wants to
develop a function that can accept 'n' arguments, that is also possible in Python. For this
purpose, a variable length argument is used in the function definition. A variable length
argument is an argument that can accept any number of values. The variable length
argument is written with a symbol before it in the function definition as:
def add(farg, *args):
Here, farg' is the formal argument and "args' represents variable length argument. We
can pass 1 or more values to this "args" and it will store them all in a tuple. A tuple is
like a list where a group of elements can be stored. In Program 19, we are showing how
to use variable length argument.
Program

A Python program to show variable length argument and its use.


def add(farg, args):
print('Formal argument', farg)
sum=0
for i in args:
sum+=1
print('Sum of all numbers= ',(farg+sum))
add(5, 10)
add(5, 10, 20, 30)
Output:
Formal argument= 5
Sum of all numbers= 15
Formal argument 5
Sum of all numbers= 65

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.

The following are different ways of writing import statement:

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)

3. from arith import.


Here "represents 'all'. In this case, PVM does not bring the module name 'arith' into our
program. Instead, it brings all the names inside the 'arith' module into our program.
That means the names add and sub are available directly to our program. Hence, we can
refer to those functions directly as add() or sub().

4. from arith import add, sub


Here, we are specifically mentioning the names of the functions add and sub. In this
case, PVM brings the names add and sub from the arith module directly into our
program. Therefore, we can call them directly as add() or sub().

A Program to import and use the arith.py module.


import arith
arith.add(10, 22)
result = arith.sub(10, 22)
print('Result of subtraction= ', result)
Output:
Sum pythonnuse-py2 of
Result of subtraction= -12

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.

from arith import *


add(10, 22)
result = sub(10, 22)
print('Result of subtraction= ', result)

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.

Python Math Module

Math Module consists of mathematical functions and constants. It is a built-in


module made for mathematical tasks. The math module provides the math
functions to deal with basic operations such as addition(+), subtraction(-),
multiplication(*), division(/), and advanced operations like trigonometric,
logarithmic, and exponential functions.

Constants in Math Module

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

Numeric & Mathematical Module:

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

Please observe the import statement in the beginning of this program.


import mypack.arith
It represents that mypack is the package (or folder) in which the arith module is found.
This arith module is being imported. When we import like this, we need to add the
package name and module name before the functions or classes that are defined inside
the module as mypack.arith.add()

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.

Python Lambda Functions


This tutorial will study anonymous, commonly called lambda functions in Python. A
lambda function can take n number of arguments at a time. But it returns only one
argument at a time. We will understand what they are, how to execute them, and their
syntax.

What are Lambda Functions in Python?


Lambda Functions in Python are anonymous functions, implying they don't have a
name. The def keyword is needed to create a typical function in Python, as we already
know. We can also use the lambda keyword in Python to define an unnamed function.
Syntax
The syntax of the Lambda Function is given below -
lambda arguments: expression
This function accepts any count of inputs but only evaluates and returns one expression.
That means it takes many inputs but returns only one output.
Lambda functions can be used whenever function arguments are necessary. In addition
to other forms of formulations in functions, it has a variety of applications in certain
coding domains. It's important to remember that according to syntax, lambda functions
are limited to a single statement.
Example
Here we share some examples of lambda functions in Python for learning purposes.

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)

The code is shown below -


def add( num ):
return num + 4
print( add(6) )
Output: 10

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.

# var1 is in the global namespace


var1 = 5
def some_func():

# var2 is in the local namespace


var2 = 6
def some_inner_func():

# var3 is in the nested local

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)

pip install numpy

Explain package Numpy with example


NumPy is the fundamental package for scientific computing with Python. NumPy stands
for "Numerical Python". It provides a high-performance multidimensional array object,
and tools for working with these arrays. An array is a table of elements (usually
numbers), all of the same type, indexed by a tuple of positive integers and represented
by a single variable. NumPy's array class is called ndarray. It is also known by the alias
array.
In NumPy arrays, the individual data items are called elements. All elements of an array
should be of the same type. Arrays can be made up of any number of dimensions.
In NumPy, dimensions are called axes. Each dimension of an array has a length which is
the total number of elements in that direction. The size of an array is the total number of
elements contained in an array in all the dimension. The size of NumPy arrays are fixed;
once created it cannot be changed again.
Numpy arrays are great alternatives to Python Lists. Some of the key advantages of
Numpy arrays are that they are fast, easy to work with, and give users the opportunity
to perform calculations across entire arrays.
A one dimensional array has one axis indicated by Axis-0. That axis has five elements in
it, so we say it has length of five.
A two dimensional array is made up of rows and columns. All rows are indicated by
Axis-0 and all columns are indicated by Axis-1. If Axis-0 in two dimensional array has
three elements, so its length it three and Axis-1 has six elements, so its length is six.
import numpy as np # alias np
Using NumPy, a developer can 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.
4. NumPy has in-built functions for linear algebra and random number generation
Example:
For NumPy with array object.
>>> import numpy as np
>>> a=np.array([1,2,3]) # one dimensional array
>>> print(a)
[123]
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array
>>> print(arr)
[[1 2 3]
[4 5 6]]
>>> type(arr)
<class 'numpy.ndarray'>
>>> print("No. of dimension: ", arr.ndim)
No. of dimension: 2
>>> print("Shape of array: ", arr.shape)
Shape of array: (2, 3)
>> >print("size of array: ", arr.size)
size of array: 6
>>> print("Type of elements in array: ", arr.dtype)
Type of elements in array: int32

23 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

>>> print("No of bytes:", arr.nbytes)


No of bytes: 24
Arrays in NumPy
import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],[ 4, 2, 5]] )
# Printing type of arr object
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)
# Printing shape of array
print("Shape of array: ", arr.shape)
# Printing size (total number of elements) of array
print("Size of array: ", arr.size)
# Printing type of elements in array
print("Array stores elements of type: ", arr.dtype)

NumPy Array Creation


import numpy as np

# Creating array from list with type float


a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)

# Creating array from tuple


b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

N-D Array Creation From List of Lists


To create an N-dimensional NumPy array from a Python List, we can use
the np.array() function and pass the list as an argument.
Create a 2-D NumPy Array
Let's create a 2D NumPy array with 2 rows and 4 columns using lists.
import numpy as np

# create a 2D array with 2 rows and 4 columns


array1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(array1)
Run Code
Output
[[1 2 3 4]
[5 6 7 8]]
In the above example, we first created a 2D list (list of lists) [[1, 2, 3, 4], [5, 6, 7,
8]] with 2 rows and 4 columns. We then passed the list to the np.array() function to
create a 2D array.
Create a 3-D NumPy Array

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

# create a 3D array with 2 "slices", each of 3 rows and 4 columns


array1 = np.array([[[1, 2, 3, 4],[5, 6, 7, 8], [9, 10, 11, 12]],
[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]])

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]]]

Check Data Type of a NumPy Array


To check the data type of a NumPy array, we can use the dtype attribute. For example,
import numpy as np

# create an array of integers


array1 = np.array([2, 4, 6])
# check the data type of array1
print(array1.dtype)
# Output: int64
Common NumPy Attributes
Here are some of the commonly used NumPy attributes:
Attributes Description

ndim returns number of dimension of the array

size returns number of elements in the array

dtype returns data type of elements in the array

shape returns the size of the array in each dimension.

returns the size (in bytes) of each elements in the


itemsize
array

returns the buffer containing actual elements of


data
the array in memory

25 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

To access the Numpy attributes, we use the . notation. For example,


array1.ndim
This returns the number of dimensions in array1.

Numpy Array ndim Attribute


The ndim attribute returns the number of dimensions in the numpy array. For example,
import numpy as np
# create a 2-D array
array1 = np.array([[2, 4, 6], [1, 3, 5]])
# check the dimension of array1
print(array1.ndim)

# Output: 2

import numpy as np

# Example matrices
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

matrix2 = np.array([[9, 8, 7],


[6, 5, 4],
[3, 2, 1]])

# Add the matrices using numpy.add()


result_matrix = np.add(matrix1, matrix2)
# Print the result matrix
print(result_matrix)

# Program to add two matrices using nested loop

X = [[1,2,3], [4 ,5,6], [7 ,8,9]]


Y = [[9,8,7], [6,5,4], [3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

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.

Why Use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant. Relevant data
is very important in data science.
What Can Pandas Do?
Pandas gives you answers about the data. Like:
Is there a correlation between two or more columns?
What is average value?
Max value?
Min value?
Pandas are also able to delete rows that are not relevant, or contains wrong values, like
empty or NULL values. This is called cleaning the data.
Installation of Pandas
If you have Python and PIP already installed on a system, then installation of Pandas is
very easy.
Install it using this command:
C:\Users\Your Name>pip install pandas
If this command fails, then use a python distribution that already has Pandas installed
like, Anaconda, Spyder etc.

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:

Example of plotting Graph


pip install matplotlib
from matplotlib import pyplot as plt
#ploting our canvas
plt.plot([1,2,3],[4,5,1])
#display the graph
plt.show()

from matplotlib import pyplot as plt


x = [5, 2, 7]
y = [1, 10, 4]
plt.plot(x, y)
plt.title('Line graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

29 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

Creating different types of graph

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.

from matplotlib import pyplot as plt


players = ['Virat','Rohit','Shikhar','Hardik']
runs = [51,87,45,67]
plt.bar(players,runs,color = 'green')
plt.title('Score Card')
plt.xlabel('Players')
plt.ylabel('Runs')
plt.show()
3. Pie Chart
A pie chart is a circular graph that is broken down in the segment or slices of pie. It is
generally used to represent the percentage or proportional data where each slice of pie
represents a particular category. Let's have a look at the below example:

from matplotlib import pyplot as plt


# Pie chart, where the slices will be ordered and plotted counter-clockwise:
Players = 'Rohit', 'Virat', 'Shikhar', 'Yuvraj'
Runs = [45, 30, 15, 10]
explode = (0.1, 0, 0, 0) # it "explode" the 1st slice

fig1, ax1 = plt.subplots()


ax1.pie(Runs, explode=explode, labels=Players, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
5. Scatter plot
The scatter plots are mostly used for comparing variables when we need to define how
much one variable is affected by another variable. The data is displayed as a collection
of points. Each point has the value of one variable, which defines the position on the
horizontal axes, and the value of other variable represents the position on the vertical
axis.

30 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

Let's consider the following simple example:


Example-1:
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
x = [5,7,10]
y = [18,10,6]
x2 = [6,9,11]
y2 = [7,14,17]
plt.scatter(x, y)
plt.scatter(x2, y2, color='g')
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

Important functions of Matplotlib


Functions Description

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.

figure() It is used to control a figure level attributes.

subplots(nrows,ncol,index) It is used to add a subplot to recent figure.

31 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

subtitle("string") It adds a common title to the plotted graph specified by the


string.

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.

bar(categorical variables, It is used to create a vertical bar graph.


values, color)

barh(categorical variables, It is used to create horizontal bar graphs.


values, color)

legend(loc) It is used to make a legend of the graph.

xtricks(index, categorical It is used to set or get the current tick locations labels of the x-
variables) axis.

pie(value, categorical It is used to create a pie chart.


variables)

hist(value, number of bins) It is used to create a histogram.

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.

axes() It is used to add axes to the recent figure.

set_xlabel("string") It is an axes level method which is used to set the x-label of the
plot specified as a string.

set_ylabel("string") It is used to set the y-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)

scatter3D(x-axis values, y- It is used to plot a three-dimension scatter plot with x- axis


axis values) value against the y-axis.

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.

It provides many user-friendly and effective numerical functions for numerical


integration and optimization.

The SciPy library supports integration, gradient optimization, special functions,


ordinary differential equation solvers, parallel programming tools, and many
more. We can say that SciPy implementation exists in every complex numerical
computation.

The scipy is a data-processing and system-prototyping environment as similar to


MATLAB. It is easy to use and provides great flexibility to scientists and engineers.

SciPy Installation
We will learn about the core functionality of SciPy. Before working with SciPy, it should
be installed in the system.

o Install SciPy using pip

We can install the SciPy library by using pip command; run the following command in
the terminal:

1. pip install scipy


o Install SciPy using Anaconda

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:

1. conda install -c anaconda scipy

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.

List of Mathematical constant

The scipy.constant provides the following list of mathematical constants.

Sr. No. Constants Description

1. pi pi

2. golden Golden ratio

Consider the following example of scipy.constant. Here we compare the 'pi' value by
importing different modules.

1. #Import pi constant from the scipy


2. from scipy.constants import pi
3. #Import pi from math package
4. from math import pi
5. #Comparing these two pi value
6. print("sciPy - pi Value = %.18f"%scipy.constants.pi)
7. print("math - pi Value = %.18f"%math.pi)

Output:

The above code will give the following output. As we can observe that both values are
same.

sciPy - pi Value = 3.141592653589793116


math - pi Value = 3.141592653589793116
Physical Constants
The scipy.constant package provides the number of physical constants. The most
commonly used physical constants are the following:

Sr. Physical Constants Description


No.

34 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

1. c Speed of light in vaccum

2. speed_of_light Speed of light in vaccum

3. G Standard acceleration of gravity

4. G Newton Constant of gravitation

5. E Elementry charge

6. R Molar gas constant

7. Alpha Fine-structure constant

8. N_A Avagadro constant

9. K Boltzmann constant

10 Sigma Stefan-Boltzmann constant σ

11. m_e Electron mass

12. m_p Proton mass

13. m_n Neutron Mass

14. H Plank Constant

15. Plank constant Plank constant h

Other important Constant


It is difficult to remember all units; the few essential constants are listed below:

Sr. Units Value


No.

1. Mass

35 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

Gram One gram in Kilogram.

Grain One grain in Kilogram.

Pound One Pound in Kilogram.

Ounce One Ounce in Kilogram.

automic_mass Atomics mass constant in Kilogram.

2. Time

Minute One minute in seconds.

Hour One hour in seconds.

Day One day in seconds.

Year One year in seconds.

3. Length

Inch One inch in meters.

Foot One foot in meters.

Yard One yard in meters.

Pt One point in meters.

Micron One Micron in meters.

4. Pressure

Atm The standard atmosphere in pascals.

Atmosphere The standard atmosphere in pascals.

Bar One bar in Pascals.

36 | P a g e
Prashant S. Bhandare
Unit 4: Python functions, modules and Packages Programming with “Python” (22616)

Torr One torr(mmHg) in pascals.

5. Area

Hectare One hectare in square meters.

Acre One acre in square meters.

6. Speed

Kmh Kilometer per hour in meter per second.

Mph Miles per hour in meter per second.

Mach One Match in meter per second.

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:

f - Function name to be integrate

a-It is a lower limit.

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)

2. from numpy import exp


3. f= lambda x:exp(-x**2)
4. i = scipy.integrate.quad(f, 0, 1)
5. print(i)

38 | P a g e
Prashant S. Bhandare

You might also like