PWP Chapter 4
PWP Chapter 4
Shubhangi Chintawar 1
What Is A Function?
● A Function is a sequence of statements/instructions that performs a
particular task.
● A function is like a black box that can take certain input(s) as its
parameters and can output a value after performing a few operations on
the parameters.
● A function is created so that one can use a block of code as many times
as needed just by using the name of the function.
2
Mrs.Shubhangi Chintawar
Why Do We Need Functions?
● Reusability
● Neat code
● Modularisation
● Easy Debugging
3
Mrs.Shubhangi Chintawar
Defining Functions In Python
A function, once defined, can be invoked as many times as needed by
using its name, without having to rewrite its code.
4
Mrs.Shubhangi Chintawar
● Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
● The input parameters or arguments should be placed within these parentheses.
● The first statement of a function is optional - the documentation string of the
function or docstring. The docstring describes the functionality of a function.
● The code block within every function starts with a colon (:) and is indented.
● All statements within the same code block are at the same indentation level.
● The return statement exits a function, optionally passing back an value to the
function caller.
Let us define a function to add two numbers.
def add(a,b):
return a+b
The above function returns the sum of two numbers a and b.
5
Mrs.Shubhangi Chintawar
The return Statement
A return statement is used to end the execution of the function call and
it “returns” the result (value of the expression following the return
keyword) to the caller.
6
Mrs.Shubhangi Chintawar
Calling/Invoking A Function
Once you have defined a function, you can call it from another
function, program, or even the Python prompt.
To use a function that has been defined earlier, you need to write a
function call.
A function call takes the following form:
<function-name> (<value-to-be-passed-as-argument>)
The function definition does not execute the function body.
The function gets executed only when it is called or invoked.
To call the above function we can write:
add(5,7)
7
Mrs.Shubhangi Chintawar
Arguments And Parameters
As you know that you can pass values to functions. For this, you define
variables to receive values in the function definition and you send
values via a function call statement.
For example, in the add() function, we have variables a and b to
receive the values and while calling the function we pass the values 5
and 7.
● Arguments: The values being passed to the function from the function call
statement are called arguments. Eg. 5 and 7 are arguments to the add() function.
9
Mrs.Shubhangi Chintawar
Scope Of Variables
All variables in a program may not be accessible at all locations in that
program.
Part(s) of the program within which the variable name is legal and
accessible, is called the scope of the variable. A variable will only be
visible to and accessible by the code blocks in its scope.
10
Mrs.Shubhangi Chintawar
Global Scope
A variable/name declared in the top-level segment (__main__) of a
program is said to have a global scope and is usable inside the whole
program (Can be accessed from anywhere in the program).
11
Mrs.Shubhangi Chintawar
Local Scope
Variables that are defined inside a function body have a local scope.
This means that local variables can be accessed only inside the function
in which they are declared.
12
Mrs.Shubhangi Chintawar
The Lifetime of a Variable
The lifetime of a variable is the time for which the variable exists in the
memory.
● The lifetime of a Global variable is the entire program run (i.e. they
live in the memory as long as the program is being executed).
13
Mrs.Shubhangi Chintawar
Creating a Global Variable
x = "Global Variable"
def foo():
print("Value of x: ", x)
foo()
Here, we created a global variable x = "Global Variable".
Then, we created a function foo to print the value of the global variable
from inside the function.
We get the output as:
Global Variable
Thus we can conclude that we can access a global variable from inside
14
any function.
Mrs.Shubhangi Chintawar
What if you want to change the value of a Global Variable from inside a
function?
x = "Global Variable"
def foo():
x = x -1
print(x)
foo()
In this code block, we tried to update the value of the global variable x.
We get an output as:
UnboundLocalError: local variable 'x' referenced before assignment
This happens because, when the command x=x-1, is interpreted, Python treats this x as
a local variable and we have not defined any local variable x inside the function foo(). 15
Mrs.Shubhangi Chintawar
Creating a Local Variable
We declare a local variable inside a function. Consider the given
function definition:
def foo():
y = "Local Variable"
print(y)
foo()
16
Mrs.Shubhangi Chintawar
Accessing A Local Variable Outside The Scope
def foo():
y = "local"
foo()
print(y)
In the above code, we declared a local variable y inside the function
foo(), and then we tried to access it from outside the function.
We get the output as:
NameError: name 'y' is not defined
We get an error because the lifetime of a local variable is the function it is defined in.
Outside the function, the variable does not exist and cannot be accessed. In other
words, a variable cannot be accessed outside its scope. 17
Mrs.Shubhangi Chintawar
Global Variable And Local Variable With The Same Name
x=5
def foo():
x = 10
print("Local:", x)
foo()
print("Global:", x)
In this, we have declared a global variable x = 5 outside the function foo(). Now,
inside the function foo(), we re-declared a local variable with the same name, x.
Now, we try to print the values of x, inside, and outside the function.
We observe the following output:
Local: 10
18
Mrs.Shubhangi Chintawar Global: 5
In the above code, we used the same name x for both global and local
variables.
We get a different result when we print the value of x because the
variables have been declared in different scopes, i.e. the local scope
inside foo() and global scope outside foo().
When we print the value of the variable inside foo() it outputs Local:
10. This is called the local scope of the variable. In the local scope, it
prints the value that it has been assigned inside the function.
Similarly, when we print the variable outside foo(), it outputs global
Global: 5.
This is called the global scope of the variable and the value of the
19
global Chintawar
Mrs.Shubhangi variable xis printed.
Python Default Parameters
Function parameters can have default values in Python. We can provide a
default value to a parameter by using the assignment operator (=).
def greet(name, wish="Happy Birthday"):
print("Hello", name + ', ' + wish)
greet("Rohan")
greet(“Hardik", "Happy New Year")
Output
Hello Rohan, Happy Birthday
Hello Hardik, Happy New Year
In this function, the parameter name does not have a default value and is required (mandatory) during a call.
On the other hand, the parameter wish has a default value of "Happy Birthday". So, it is optional during a call.
If an argument is passed corresponding to the parameter, it will overwrite the default value, otherwise it will use
the default value. 20
Mrs.Shubhangi Chintawar
Prime number Program
def isPrime(n):
for d in range(2,n):
if(n%d==0):
break
else:
return True
return False
Output:-
isPrime(12)
False
21
Mrs.Shubhangi Chintawar
Program to reverse the given number using function
def reverse(n):
rev=0
while(n>0): Output:-
r=n%10 Enter a number:
rev=(rev*10)+r 123
n=n//10 Reverse of 123 is 321
return rev
print("Enter a number:")
n=int(input())
reverseno=reverse(n)
print("Reverse of ",n," is ",reverseno)
22
Mrs.Shubhangi Chintawar
WAP to find out factorial of a number using function.
WAP to find list of prime numbers from given range using function
WAP to check whether number is armstrong number or not.
23
Mrs.Shubhangi Chintawar
Python Built in functions
abs( ) function
The abs() function returns the absolute value of the specified number.
Return the absolute value of a negative number:
negative_number = -676
print(abs(negative_number))
Output:
676
24
Mrs.Shubhangi Chintawar
pow( ) function
The pow() function returns the calculated value of x to the power of y
i.e, xy.
If a third parameter is present in this function, then it returns x to the
power of y, modulus z.
Output:
25
81
Mrs.Shubhangi Chintawar
dir( ) function
The dir() function returns all the properties and methods of the
specified object, without the values.
This function even returns built-in properties which are the default for
all objects.
26
Mrs.Shubhangi Chintawar
27
Mrs.Shubhangi Chintawar
The all() accept an iterable objects such as list, dictionary etc.
The all() function returns True if all items in an iterable are true,
otherwise it returns False.
If the iterable object is empty, the all() function also returns True.
# Returns False because both the first and the third items are False
28
Mrs.Shubhangi Chintawar
myset = {0, 1, 0}
x = all(myset)
print(x)
# Returns False because both the first and the third items are False
mylist = [2, 1, 1]
x = all(mylist)
print(x)
# Returns True
29
Mrs.Shubhangi Chintawar
mylist = [ ]
x = all(mylist)
print(x)
# True
30
Mrs.Shubhangi Chintawar
The bin() function returns the binary version of a specified integer.
The result will always start with the prefix 0b.
Output:
0b1010
31
Mrs.Shubhangi Chintawar
Python bool()
The python bool() converts a value to boolean(True or False) using the
standard truth testing procedure.
Python bool() Example
# Returns False as x is False
x = False
print(bool(x))
33
Mrs.Shubhangi Chintawar
Python callable() Function
A python callable() function in Python is something that can be called.
This built-in function checks and returns true if the object passed
appears to be callable, otherwise false.
Python callable() Function Example
x=8 def x():
print(callable(x)) a=5
Output: False print(callable(x))
Output: True
34
Mrs.Shubhangi Chintawar
Python sum() Function
Python sum() function is used to get the sum of numbers of an iterable,
i.e., list.
Python sum() Function Example
s = sum([1, 2,4 ])
print(s)
s = sum([1, 2, 4], 10)
print(s)
Output:
7
35
17
Mrs.Shubhangi Chintawar
Python any() Function
The python any() function returns true if any item in an iterable is true.
Otherwise, it returns False.
l = [4, 3, 2, 0] Output:
print(any(l)) True
l = [0, False]
False
print(any(l)) True
False
# Some elements of list are true while others are false
l = [ 1, 0, 6, 7, False]
print(any( l ))
l = []
print(any(l)) 36
Mrs.Shubhangi Chintawar
Python float()
The python float() function returns a floating-point number from a
number or string.
# for integers Output:
print(float(9))
9.0
# for floats 8.19
print(float(8.19)) -24.27
a = (1, 5, 3, 9)
x = max(a)
print(x)
38
9
Mrs.Shubhangi Chintawar
The min() function returns the item with the lowest value, or the item
with the lowest value in an iterable.
If the values are strings, an alphabetically comparison is done.
x = min(5, 10)
print(x)
39
Mrs.Shubhangi Chintawar
The oct() function converts an integer into an octal string.
0o14
40
Mrs.Shubhangi Chintawar
The ord() function returns the number representing the unicode code
of a specified character.
x = ord("h")
print(x)
104
41
Mrs.Shubhangi Chintawar
The chr() function returns the character that represents the specified
unicode.
x = chr(97)
print(x)
42
Mrs.Shubhangi Chintawar
The hex() function converts the specified number into a hexadecimal
value.
The returned string always starts with the prefix 0x.
x = hex(255)
print(x)
0xff
43
Mrs.Shubhangi Chintawar
Python Modules
● A module allows to logically organize your Python code.
● Grouping related code into a module makes the code easier to
understand and use.
● A Module is a file consisting of Python code.
● A module can define functions, classes and variables.
44
Mrs.Shubhangi Chintawar
Example: create a simple module
45
Mrs.Shubhangi Chintawar
Import Module in Python – Import statement
We can import the functions, classes defined in a module to another
module using the import statement in some other Python source file.
Syntax:
import module
46
Mrs.Shubhangi Chintawar
Example: Importing modules in Python
# importing module myadd.py
>>>import myadd
>>>print(myadd.add(10, 2))
Output:
12
47
Mrs.Shubhangi Chintawar
Write a module for displaying fibonacci series
fibseries.py
def fib(n):
a,b=0,1 >>>import fibseries
while b<n: >>>fibseries.fib(10)
1
print(b) 1
a,b=b,a+b 2
3
print()
5
8
48
Mrs.Shubhangi Chintawar
The from import Statement
Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
Example: Importing specific attributes from the module
cal.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
def mul(x,y):
return (x*y)
49
Mrs.Shubhangi Chintawar
>>>from cal import mul
>>>mul(2,3))
Output:
6
50
Mrs.Shubhangi Chintawar
The from import Statement
Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
Example: Importing specific attributes from the module
51
Mrs.Shubhangi Chintawar
52
Mrs.Shubhangi Chintawar
cos(x) Returns the cosine of x
53
Mrs.Shubhangi Chintawar
import math
5.0
print(math.sqrt(25))
3.14159265359
print(math.pi)
114.591559026
print(math.degrees(2))
1.0471975512
print(math.radians(60))
0.909297426826
print(math.sin(2))
0.87758256189
print(math.cos(0.5)) 0.234143362351
print(math.tan(0.23)) 24
print(math.factorial(4))
54
Mrs.Shubhangi Chintawar
Random module
To pick random number in a given range, pick a random number from a
list.
import random
print(random.random())
#uniform() method returns a random floating number between the two specified numbers
print(random.uniform(20, 60))
#randint() method returns an integer number selected element from the specified range.
print(random.randint(3, 9))
55
Mrs.Shubhangi Chintawar
The randrange() method returns a randomly selected element from the
specified range.
import random
print(random.randrange(3, 9)) 3
print(random.randrange(9)) 2
print(random.randrange(3, 9,2)) 7
56
Mrs.Shubhangi Chintawar
Python statistics Module
Python has a built-in module that you can use to calculate mathematical
statistics of numeric data.
59
Mrs.Shubhangi Chintawar
The statistics.stdev() method calculates the standard deviation from a
sample of data.
Standard deviation is a measure of how spread out the numbers are.
A large standard deviation indicates that the data is spread out,
A small standard deviation indicates that the data is clustered closely
around the mean.
# Import statistics Library
import statistics
# Calculate the standard deviation from a sample of data
print(statistics.stdev([1, 3, 5, 7, 9, 11])) #3.74165
print(statistics.stdev([2, 2.5, 1.25, 3.1, 1.75, 2.8])) #0.6925
print(statistics.stdev([1, 30, 50, 100])) #41.6763
60
Mrs.Shubhangi Chintawar
Mean xbar=45.25
61
Mrs.Shubhangi Chintawar
Calendar
Python defines an inbuilt module calendar that handles operations
related to the calendar.
The calendar module allows output calendars like the program and
provides additional useful functions related to the calendar.
62
Mrs.Shubhangi Chintawar
Display the Calendar of a given month.
import calendar
63
Mrs.Shubhangi Chintawar
>>>print(calendar.calendar(2022))
64
Mrs.Shubhangi Chintawar
Functional Programming Modules
The modules provide functions and classes that support a functional
programming style, and general operations on callables.
65
Mrs.Shubhangi Chintawar
1. itertool module
Provides various ways to manipulate the sequence while traversing.
chain() accepts multiple iterables and return a single sequence as if
all items belong to that sequence.
from itertools import *
for value in chain([1.3,2.51,3.3],['C++','python','java']):
print(value)
1.3
2.51
3.3
C++
python
java
66
Mrs.Shubhangi Chintawar
cycle() function iterate through a sequence upto infinite. This works
just like a circular linked list.
from itertools import *
index=0
for item in cycle(['c++','python','java']):
index=index+1 c++
python
if index==10: java
break c++
python
print(item) java
c++
python
java
67
Mrs.Shubhangi Chintawar
Functools module is for higher-order functions that work on other
functions.
It provides functions for working with other functions and callable
objects to use or extend them without completely rewriting them.
Example
def multiplier(x,y):
return x*y
68
Mrs.Shubhangi Chintawar
If we want to make dedicated func to duble and triple a number then
We will have to define new functions as:
def multiplier (x,y):
return x*y
def doubleit(x):
return multiplier(x,2)
def tripleit(x):
return multiplier(x,3)
69
Mrs.Shubhangi Chintawar
Use partial function:
from functools import partial
def multiplier(x,y):
return x*y
double=partial(multiplier, y=2)
triple=partial(multiplier,y=3)
print(‘Double:-’. double(5))
print(‘Triple:-’. double(5))
Output:-
Double=10
70
Triple=15
Mrs.Shubhangi Chintawar
Operator Module
Python has predefined functions for many mathematical, logical, relational,
bitwise etc operations under the module “operator”. Some of the basic
functions are covered in this article.
72
Mrs.Shubhangi Chintawar
Packages
A Python package usually consists of several modules.
Packages are namespace which contain multiple modules.
They are simple directories.
Packages allows for hierarchical structuring of the module namespace
using dot notation.
Package is collection of modules and _init_.py file.
__init__.py helps the Python interpreter to recognise the folder as
package.
It also specifies the resources to be imported from the modules.
73
Mrs.Shubhangi Chintawar
Creating Package
Let’s create a package named mypckg that will contain two modules p1
and p2. To create this module follow the below steps –
74
Mrs.Shubhangi Chintawar
p1.py
def m1(): The hierarchy of the our
print("first module") package looks like this –
mypkg
|
p2.py
|
def m2(): ---__init__.py
print("second module") |
|
---p1.py
|
|
---p2.py
75
Mrs.Shubhangi Chintawar
>>>import mypkg.p1,mypkg.p2
>>>mypkg.p1.m1()
first module
>>>mypkg.p2.m2()
second module
76
Mrs.Shubhangi Chintawar
>>>from mypkg import p1,p2
>>>p1.m1()
first module
>>>p2.m2()
second module
77
Mrs.Shubhangi Chintawar
>>>from mypkg.mypkg2.p3 import m3
>>>m3()
third module
78
Mrs.Shubhangi Chintawar
NumPy, -Numerical Python,
● It is a library consisting of multidimensional array objects and a collection of
routines for processing those arrays.
● Using NumPy, mathematical and logical operations on arrays can be
performed.
● In Python we have lists that serve the purpose of arrays, but they are slow to
process.
● NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
● The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
● Arrays are very frequently used in data science, where speed and resources are
very important.
79
Mrs.Shubhangi Chintawar
Installation of NumPy
80
Mrs.Shubhangi Chintawar
● NumPy is the fundamental package for scientific computing in Python.
81
Mrs.Shubhangi Chintawar
Import NumPy
Once NumPy is installed, import it in your applications by adding the
import keyword:
import numpy
NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same
thing.
import numpy as np
82
Mrs.Shubhangi Chintawar
import numpy as np
print(arr)
[1 2 3 4 5]
83
Mrs.Shubhangi Chintawar
Create a NumPy ndarray Object
NumPy is used to work with arrays.
The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) [1 2 3 4 5]
print(type(arr)) <class 'numpy.ndarray'>
84
Mrs.Shubhangi Chintawar
To create an ndarray, we can pass a list, tuple or any array-like object
into the array() method, and it will be converted into an ndarray:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
[1 2 3 4 5]
85
Mrs.Shubhangi Chintawar
Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
0-D Arrays
0-D arrays are the elements in an array. Each value in an array is a 0-D
array.
import numpy as np
arr = np.array(42)
print(arr)
86
Mrs.Shubhangi Chintawar
1-D Arrays
These are the most common and basic arrays.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
87
Mrs.Shubhangi Chintawar
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
[[1 2 3]
[4 5 6]]
88
Mrs.Shubhangi Chintawar
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D
array.
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]] 89
Mrs.Shubhangi Chintawar
Check Number of Dimensions?
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
0
print(c.ndim) 1
print(d.ndim) 2
3
90
Mrs.Shubhangi Chintawar
Array Indexing
import numpy as np 1
arr = np.array([1, 2, 3, 4]) 7
print(arr[0]) 2nd element on 1st row: 2
print(arr[2] + arr[3]) 5th element on 2nd row: 10
6
arr1 = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr1[0, 1])
print('5th element on 2nd row: ', arr1[1, 4])
arr2 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr2[0, 1, 2])
91
Mrs.Shubhangi Chintawar
Slicing of Array
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
[2 3 4 5]
print(arr[1:5])
[5 6 7]
print(arr[4:])
[1 2 3 4]
print(arr[:4])
[5 6]
print(arr[-3:-1])
[2 4]
print(arr[1:5:2])
[1 3 5 7]
print(arr[::2])
print()
arr1 = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
[7 8 9]
print(arr1[1, 1:4])
[3 8]
print(arr1[0:2, 2])
[[2 3 4]
print(arr1[0:2, 1:4])
Mrs.Shubhangi Chintawar [7 8 9]] 92
import numpy as np
93
Mrs.Shubhangi Chintawar
Reshaping arrays
Reshaping means changing the shape of an array.
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number of
elements in each dimension.
94
Mrs.Shubhangi Chintawar
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) [[ 1 2 3]
[ 4 5 6]
newarr = arr.reshape(4, 3) [ 7 8 9]
print(newarr) [10 11 12]]
print() [[[ 1 2]
[ 3 4]
newarr = arr.reshape(2, 3, 2) [ 5 6]]
print(newarr)
[[ 7 8]
[ 9 10]
[11 12]]]
95
Mrs.Shubhangi Chintawar
Joining NumPy Arrays
import numpy as np
arr1 = np.array([1, 2, 3]) [1 2 3 4 5 6]
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2)) [[1 2]
print(arr)
[3 4]
print()
[5 6]
[7 8]
arr3 = np.array([[1, 2], [3, 4]])
[5 6]
arr4 = np.array([[5, 6], [7, 8]])
[7 8]]
arr6 = np.array([[5, 6], [7, 8]])
arr5 = np.concatenate((arr3, arr4,arr6))
[[1 2 5 6]
print(arr5)
[3 4 7 8]]
print()
arr7 = np.concatenate((arr3, arr4),axis=1)
96
print(arr7)
Mrs.Shubhangi Chintawar
Scipy
● SciPy is a scientific computation library that uses NumPy for more
mathematical functions.
● SciPy stands for Scientific Python.
● It provides more utility functions for optimization and signal
processing.
● Like NumPy, SciPy is open source so we can use it freely.
● SciPy has optimized and added functions that are frequently used in
NumPy and Data Science.
97
Mrs.Shubhangi Chintawar
Installation of SciPy
C:\Users\Your Name>pip install scipy
98
Mrs.Shubhangi Chintawar
99
Mrs.Shubhangi Chintawar
Constants in SciPy
As SciPy is more focused on scientific implementations, it provides
many built-in scientific constants.
These constants can be helpful when you are working with Data
Science.
3.1415926
100
Mrs.Shubhangi Chintawar
Binary Prefixes:
Return the specified unit in bytes (e.g. kibi returns 1024)
from scipy import constants
print(constants.kibi) 1024
print(constants.mebi) 1048576
1073741824
print(constants.gibi) 1099511627776
1125899906842624
print(constants.tebi) 1152921504606846976
1180591620717411303424
print(constants.pebi) 1208925819614629174706176
print(constants.exbi)
print(constants.zebi)
print(constants.yobi)
101
Mrs.Shubhangi Chintawar
SciPy Linear Algebra – SciPy Linalg
The SciPy package includes the features of the NumPy package in
Python.
It uses NumPy arrays as the fundamental data structure.
It has all the features included in the linear algebra of the NumPy
module and some extended functionality.
It consists of a linalg submodule, and there is an overlap in the
functionality provided by the SciPy and NumPy submodules.
102
Mrs.Shubhangi Chintawar
Solving the linear equations
7x + 2y = 8
4x + 5y = 10
from scipy import linalg
import numpy as np [0.74074074 1.40740741]
a = np.array([[7, 2], [4, 5]])
b = np.array([8, 10])
res = linalg.solve(a, b)
print(res)
103
Mrs.Shubhangi Chintawar
Calculating the Inverse of a Matrix
The scipy.linalg.inv is used to find the inverse of a matrix
from scipy import linalg
import numpy as np
x = np.array([[7, 2], [4, 5]])
y = linalg.inv(x)
[[ 0.18518519 -0.07407407]
print(y) [-0.14814815 0.25925926]]
104
Mrs.Shubhangi Chintawar
Finding the Determinant of a Matrix
The determinant of a square matrix is a value derived arithmetically
from the coefficients of the matrix. In the linalg module, we use the
linalg.det() function to find the determinant of a matrix.
from scipy import linalg
import numpy as np
A = np.array([[9 , 6] , [4 , 5]])
D = linalg.det(A) 21.0
print(D)
105
Mrs.Shubhangi Chintawar
Matplotlib is a low level graph plotting library in python that serves as
a visualization utility.
Matplotlib consists of several plots like line, bar, scatter, histogram etc.
Installation of Matplotlib
C:\Users\Your Name>pip install matplotlib
106
Mrs.Shubhangi Chintawar
Line plot :
107
Mrs.Shubhangi Chintawar
Bar Graph
from matplotlib import pyplot as plt
x=[2,4,8,10]
y=[2,8,8,2]
plt.xlabel('X-axis')
Text(0.5, 0, 'X-axis')
plt.ylabel('Y-Axis')
Text(0, 0.5, 'Y-Axis')
plt.bar(x,y,label="Graph",color='b’,width=.5)
<BarContainer object of 4 artists>
plt.show()
108
Mrs.Shubhangi Chintawar
A histogram is basically used to represent data provided in a form of
some groups.
It is accurate method for the graphical representation of numerical data
distribution.
It is a type of bar plot where X-axis represents the bin ranges while
Y-axis gives information about frequency.
useful for arrays or a very long list.
109
Mrs.Shubhangi Chintawar
from matplotlib import pyplot as plt
y=[1,1,2,2,2,2,2,3,3,3,3,4,4,5]
plt.hist(y)
(array([2., 0., 5., 0., 0., 4., 0., 2., 0., 1.]), array([1. , 1.4, 1.8, 2.2, 2.6, 3. ,
3.4, 3.8, 4.2, 4.6, 5. ]), <BarContainer object of 10 artists>)
plt.show()
110
Mrs.Shubhangi Chintawar
Scatter plots are used to observe relationship between variables and
uses dots to represent the relationship between them.
The scatter() method in the matplotlib library is used to draw a scatter
plot.
Scatter plots are widely used to represent relation among variables and
how change in one affects the other.
111
Mrs.Shubhangi Chintawar
from matplotlib import pyplot as plt
x=[5,2,9,4,7]
y=[10,5,8,4,2]
plt.scatter(x,y)
<matplotlib.collections.PathCollection object at
0x00000123A88E9540>
plt.show()
112
Mrs.Shubhangi Chintawar
Pandas
Pandas is an open-source library that is made mainly for working with
relational or labeled data both easily.
Pandas is fast and it has high performance & productivity for users.
113
Mrs.Shubhangi Chintawar
Installing Pandas:
pip install pandas
114
Mrs.Shubhangi Chintawar
Series:
Pandas Series is a one-dimensional labelled array capable of holding
data of any type (integer, string, float, python objects, etc.).
115
Mrs.Shubhangi Chintawar
A pandas Series can be created using the following constructor −
pandas.Series( data, index, dtype, copy)
116
Mrs.Shubhangi Chintawar
>>>import pandas as pd
>>>import numpy as np
>>>numpy_arr=np.array([2,4,6,8,10,20])
>>>si=pd.Series(numpy_arr)
>>>print(si)
0 2
1 4
2 6
3 8
4 10
5 20
117
dtype: int32
Mrs.Shubhangi Chintawar
import pandas as pd
data=[10,20,30,40,50]
index=['a','b','c','d','e']
si=pd.Series(data,index)
si
a 10
b 20
c 30
d 40
e 50
dtype: int64
118
Mrs.Shubhangi Chintawar
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data)
s
a 0.0
b 1.0
c 2.0
dtype: float64
119
Mrs.Shubhangi Chintawar
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
s
b 1.0
c 2.0
d NaN
a 0.0
dtype: float64
120
Mrs.Shubhangi Chintawar
Pandas DataFrame is two-dimensional size-mutable, potentially
heterogeneous tabular data structure with labeled axes (rows and
columns).
121
Mrs.Shubhangi Chintawar
pandas.DataFrame(data, index, columns, dtype, copy)
122
Mrs.Shubhangi Chintawar
import pandas as pd
data = { calories duration
0 420 50
"calories": [420, 380, 390], 1 380 40
2 390 45
"duration": [50, 40, 45]
} print(df.loc[0])
#load data into a DataFrame object: calories 420
duration 50
df = pd.DataFrame(data) Name: 0, dtype: int64
print(df)
print(df.loc[0])
calories duration
print(df.loc[[0, 1]]) 0 420 50
1 380 40
123
Mrs.Shubhangi Chintawar
import pandas as pd
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# select two columns Name Qualification
0 Jai Msc
print(df[['Name', 'Qualification']]) 1 Princi MA
2 Gaurav MCA
3 Anuj Phd
124
Mrs.Shubhangi Chintawar
In Pandas, Panel is a very important container for three-dimensional data.
pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)
Data:- Data takes various forms like ndarray, series, map, lists, dict,
constants and also another DataFrame
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4
126
Mrs.Shubhangi Chintawar
Test
1. What is function , explain with example (4)
2. WAP to explain the difference between global and local variable.
3. Write a procedure to create user defined package.
4. WAP to create two matrices and perform addition, sub,mul, and
division operation on matrix.(hint:- use numpy)
5. WAP that will display Calendar of given month using calendar module.
6. WAP to generate random float values between 5 to 50 using random
module.
7. WAP to generate six random integer numbers between 20 and 50.
127
Mrs.Shubhangi Chintawar