Python Chapter-10,11,12,13

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Python Programming

CHAPTER-10
MODULES and PACKAGES

What are modules in Python?


Modules refer to a file containing Python statements and definitions.

Create a Module
To create a module just save the code you want in a file with the file extension .py
Example: Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement
Example: Import the module named mymodule, and call the greeting function
import mymodule

mymodule.greeting("Jonathan")

Example:
# Python Module example for addition of two numbers
<------ addition.py------>
def add(a, b):
result = a + b
return result
<------ example.py------>
import addition
addition.add(10,20)

Namespace in Python
In python we deal with variables, functions, libraries and modules etc. There is a chance the
name of the variable you are going to use is already existing as name of another variable or as the
name of another function or another method. In such scenario, we need to learn about how all these
names are managed by a python program. This is the concept of namespace.
Following are the three categories of namespace
1) Local Namespace: All the names of the functions and variables declared by a program are held in
this namespace. This namespace exists as long as the program runs.
2) Global Namespace: This namespace holds all the names of functions and other variables that are
included in the modules being used in the python program. It encompasses all the names that are
part of the Local namespace.
3) Built-in Namespace: This is the highest level of namespace which is available with default names
available as part of the python interpreter that is loaded as the programing environment. It
encompasses Global Namespace which in turn encompasses the local namespace.

Govt. Polytechnic, Arakere, Srirangapatna Page 1


Python Programming

Example:
a = 10 # global variable
def function_local( ):
b=20
a=30 # local variable
print(a)
print(b)
def function_inner( ):
b=35
a=25
print(a)
print(b)
function_inner( )

function_local( ) #function call

print(a)

Output:
30
20
25
35
10

Govt. Polytechnic, Arakere, Srirangapatna Page 2


Python Programming

Packages
Packages are a way of structuring many packages and modules which help in a well-
organized hierarchy of data set, making the directories and modules easy to access.

To tell Python that a particular directory is a package, we create a file named __init__.py inside it an d
then it is considered as a package and we may create other modules and sub-packages within it.
This __init__.py file can be left blank or can be coded with the initialization code for the package.

To create a package in Python, we need to follow these three simple steps:


1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the directory is a
package.

< --------- __init__.py ----------->


Blank

< --------- add.py ----------->

def addition(a,b):
print(a+b)

Program using package:

from calculator import add


add.addition(10,20)

Output:
30

Govt. Polytechnic, Arakere, Srirangapatna Page 3


Python Programming

Pip install emoji

Govt. Polytechnic, Arakere, Srirangapatna Page 4


Python Programming

CHAPTER-11
NumPy
What is NumPy?
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
NumPy stands for Numerical Python.

Why Use NumPy?


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.

Why is NumPy Faster Than Lists?


➢ NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access
and manipulate them very efficiently.
➢ This behavior is called locality of reference in computer science.
➢ This is the main reason why NumPy is faster than lists. Also it is optimized to work with latest CPU
architectures.

Install numpy

pip install numpy

Example:
import numpy

arr = numpy.array([1, 2, 3, 4, 5])


print(arr)

Output
[1, 2, 3, 4, 5]

Govt. Polytechnic, Arakere, Srirangapatna Page 5


Python Programming

NumPy as np
NumPy is usually imported under the np alias.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


print(arr)
print(np.__version__) # Check version

Ouput:
[1 2 3 4 5]
1.19.2

NOTE:
type( ): This built-in Python function tells us the type of the object passed to it. Like in above code it
shows that arr is numpy.ndarray type.

Indexing

import numpy as np

arr = np.array([1, 2, 3, 4])


print(arr[3])

Ouput:
4

Access 2-D Arrays


To access elements from 2-D arrays we can use comma separated integers representing the
dimension and the index of the element.
Think of 2-D arrays like a table with rows and columns, where the row represents the dimension and
the index represents the column.

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])


print('2nd element on 1st row: ', arr[0, 1])

Ouput:
2nd element on 1st row: 2

Govt. Polytechnic, Arakere, Srirangapatna Page 6


Python Programming

Access 3-D Arrays


To access elements from 3-D arrays we can use comma separated integers representing the
dimensions and the index of the element.

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])

Ouput:
6

Negative Indexing
Use negative indexing to access an array from the end.

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])


print('Last element from 2nd dim: ', arr[1, -1])

Ouput:
10

Slicing arrays
Slicing in python means taking elements from one given index to another given index.
We pass slice instead of index like this: [start:end]
We can also define the step, like this: [start:end:step]

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])


print(arr[1:5])

Ouput:
2, 3, 4, 5

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])


print(arr[:4])

Ouput:
[1 2 3 4]
Govt. Polytechnic, Arakere, Srirangapatna Page 7
Python Programming

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])


print(arr[-3:-1])

Ouput:
[5 6]

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])


print(arr[1:5:2])

Ouput:
[2, 4]

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])


print(arr[::2])

Ouput:
[1, 3, 5, 7]

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])


print(arr[0:2, 2])

Ouput:
[3, 8]

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])


print(arr[0:2, 1:4])

Ouput:
[[2 3 4]
[7 8 9]]

Govt. Polytechnic, Arakere, Srirangapatna Page 8


Python Programming

Arithmetic operations
add( ), subtract( ), multiply( ), and divide( )

a = np.array([1,3,5,7])
b = np.array([2,4,6,8])

print(a)
print(b)

print(np.add(a,b))
print(np.subtract(a,b))
print(np.multiply(a,b))
print(np.divide(a,b))
print(np.square(a))

Ouput:
[1 3 5 7]
[2 4 6 8]
[ 3 7 11 15]
[-1 -1 -1 -1]
[ 2 12 30 56]
[0.5 0.75 0.83333333 0.875 ]
[ 1 9 25 49]

NumPy package for manipulation functions


reshape( ):This function gives a new shape to an array without changing the data.

import numpy as np
a = np.arange(8)
print('The original array:')
print(a)

b = a.reshape(4,2)
print('The modified array:')
print(b)

Output:
The original array:
[0 1 2 3 4 5 6 7]
The modified array:
[[0 1]
[2 3]
[4 5]
[6 7]]

Govt. Polytechnic, Arakere, Srirangapatna Page 9


Python Programming

transpose( ):This function permutes the dimension of the given array. It returns a view wherever
possible.

import numpy as np

a = np.arange(12).reshape(3,4)

print('The original array is:')


print(a)

print('The transposed array is:')


print(np.transpose(a))

Output:
The original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
The transposed array is:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]

squeeze( ):This function removes one-dimensional entry from the shape of the given array. Two
parameters are required for this function.

import numpy as np

x = np.arange(9).reshape(1,3,3)
print('Array X:')
print(x)

y = np.squeeze(x)
print('Array Y:')
print(y)

print('The shapes of X and Y array:')


print(x.shape, y.shape)

Output:
Array X:
[[[0 1 2]
[3 4 5]
[6 7 8]]]

Govt. Polytechnic, Arakere, Srirangapatna Page 10


Python Programming

Array Y:
[[0 1 2]
[3 4 5]
[6 7 8]]
The shapes of X and Y array:
(1, 3, 3) (3, 3)

concatenate( ):
Concatenation refers to joining. This function is used to join two or more arrays of the same shape
along a specified axis.

import numpy as np
a = np.array([[1,2],[3,4]])

print('First array:')
print(a)

b = np.array([[5,6],[7,8]])

print('Second array:')
print(b)

# both the arrays are of same dimensions

print('Joining the two arrays along axis 0:')


print(np.concatenate((a,b)))

Output:
First array:
[[1 2]
[3 4]]

Second array:
[[5 6]
[7 8]]

Joining the two arrays along axis 0:


[[1 2]
[3 4]
[5 6]
[7 8]]

Govt. Polytechnic, Arakere, Srirangapatna Page 11


Python Programming

append( ):This function adds values at the end of an input array. The append operation is not inplace,
a new array is allocated. Also the dimensions of the input arrays must match otherwise ValueError
will be generated.

import numpy as np

a = np.array([[1,2,3],[4,5,6]])

print('First array:')
print(a)

print('Append elements to array:')


print(np.append(a, [7,8,9]))

Output:
First array:
[[1 2 3]
[4 5 6]]
Append elements to array:
[1 2 3 4 5 6 7 8 9]

split( ):This function divides the array into subarrays along a specified axis.

import numpy as np

a = np.arange(9)

print('First array:')
print(a)

print('Split the array in 3 equal-sized subarrays:')


b = np.split(a,3)
print(b)

Output:
First array:
[0 1 2 3 4 5 6 7 8]
Split the array in 3 equal-sized subarrays:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]

Govt. Polytechnic, Arakere, Srirangapatna Page 12


Python Programming

NumPy statistical functions


NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile
standard deviation and variance, etc.

1. np.amin( )- This function determines the minimum value of the element along a specified axis.
2. np.amax( )- This function determines the maximum value of the element along a specified axis.
3. np.mean( )- It determines the mean value of the data set.
4. np.median( )- It determines the median value of the data set.
5. np.std( )- It determines the standard deviation
6. np.var( ) – It determines the variance.
7. np.ptp( )- It returns a range of values along an axis.
8. np.average( )- It determines the weighted average
9. np.percentile( )- It determines the nth percentile of data along the specified axis.

numpy.amin( ) and numpy.amax( )


These functions return the minimum and the maximum from the elements in the given array along
the specified axis.

import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])

print('Our array is:')


print(a)

print('Applying amin( ) function:')


print(np.amin(a,1))

print('Applying amin( ) function again:')


print(np.amin(a,0))

print('Applying amin( ) function:')


print(np.amin(a))

print('Applying amax( ) function:')


print(np.amax(a))

print('Applying amax( ) function again:')


print(np.amax(a, axis = 0))

print('Applying amax() function again:')


print(np.amax(a, axis = 1))

Govt. Polytechnic, Arakere, Srirangapatna Page 13


Python Programming

Output:
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]
Applying amin() function:
[3 3 2]
Applying amin() function again:
[2 4 3]
Applying amin() function:
2
Applying amax() function:
9
Applying amax() function again:
[8 7 9]
Applying amax() function again:
[7 8 9]

Pandas
Pandas is a Python library.
Pandas is used to analyze data.

What is Pandas?
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.

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
import Pandas
Once Pandas is installed, import it in your applications by adding the import keyword:

Govt. Polytechnic, Arakere, Srirangapatna Page 14


Python Programming

import pandas

Pandas as pd
Pandas is usually imported under the pd alias.
alias: In Python alias are an alternate name for referring to the same thing.

Create an alias with the as keyword while importing:


import pandas as pd
Checking Pandas Version
The version string is stored under __version__ attribute.
print(pd.__version__)

1.1.3

What is a Series?
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.

import pandas as pd

a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)

Output:
0 1
1 7
2 2

Create Labels
With the index argument, you can name your own labels.

import pandas as pd

a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)

Output:
x 1
y 7
z 2

Govt. Polytechnic, Arakere, Srirangapatna Page 15


Python Programming

What is a DataFrame?
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with
rows and columns.

import pandas as pd

data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}

#load data into a DataFrame object:


df = pd.DataFrame(data)

print(df)

Output:
calories duration
0 420 50
1 380 40
2 390 45

Locate Row
As you can see from the result above, the DataFrame is like a table with rows and columns.
Pandas use the loc attribute to return one or more specified row(s)

print(df.loc[0])

Output:
calories 420
duration 50

#use a list of indexes:


print(df.loc[[0, 1]])

Output:
calories duration
0 420 50
1 380 40

Govt. Polytechnic, Arakere, Srirangapatna Page 16


Python Programming

Named Indexes
With the index argument, you can name your own indexes.

import pandas as pd

data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}

df = pd.DataFrame(data, index = ["day1", "day2", "day3"])


print(df)

Output:
calories duration
day1 420 50
day2 380 40
day3 390 45

Column Selection: In Order to select a column in Pandas DataFrame, we can either access the columns
by calling them by their columns name.

#select particluar column


print(df[['calories']])

Output:
calories
day1 420
day2 380
day3 390

The aggregate functions that are available in the Pandas package:

• count( ) – Count the number of non-null observation.


• sum( ) – sum of all the values / list
• min( ) – Minimum value
• max( ) – maximum value
• mean( ) – Arthmetic Mean
• median( ) – Arthmetic median()
• mode( ) – Mode
• std( ) – standard deviation
• var( ) – variance .

Govt. Polytechnic, Arakere, Srirangapatna Page 17


Python Programming

Example Program

import pandas as pd
points_table = {'Team_':['MI', 'CSK', 'Devils', 'MI', 'CSK',
'RCB', 'CSK', 'CSK', 'KKR', 'KKR', 'KKR', 'RCB'],
'Rank_' :[1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],
'Year_' :[2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Point_':[876,789,863,673,741,812,756,788,694,701,804,690]}
df = pd.DataFrame(points_table)
print(df)

Output:
Team_ Rank_ Year_ Point_
0 MI 1 2014 876
1 CSK 2 2015 789
2 Devils 2 2014 863
3 MI 3 2015 673
4 CSK 3 2014 741
5 RCB 4 2015 812
6 CSK 1 2016 756
7 CSK 1 2017 788
8 KKR 2 2016 694
9 KKR 4 2014 701
10 KKR 1 2015 804
11 RCB 2 2017 690

Rename:

df.rename(columns={"Point": "Points", "Team": "Team Name"}).head()

Govt. Polytechnic, Arakere, Srirangapatna Page 18


Python Programming

CHAPTER-12
FILES
Files are named locations on disk to store related information. They are used to permanently
store data in a non-volatile memory (e.g. hard disk).

When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
1) Open a file
2) Read or write (perform operation)
3) Close the file

Opening Files in Python


Python has a built-in open() function to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.

f = open("test.txt") # open file in current directory


f = open("C:/Python38/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read r,
write w or append a to the file. We can also specify if we want to open the file in text mode or binary
mode.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing
with non-text files like images or executable files.
Mode Description

R Opens a file for reading. (default)

Opens a file for writing. Creates a new file if it does not exist or
W
truncates the file if it exists.

Opens a file for exclusive creation. If the file already exists, the
X
operation fails.

Opens a file for appending at the end of the file without truncating
A
it. Creates a new file if it does not exist.

T Opens in text mode. (default)

B Opens in binary mode.

+ Opens a file for updating (reading and writing)

Govt. Polytechnic, Arakere, Srirangapatna Page 19


Python Programming

f = open("test.txt") # equivalent to 'r' or 'rt'


f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode

When working with files in text mode, it is highly recommended to specify the encoding type.
f = open("test.txt", mode='r', encoding='utf-8')

Closing Files in Python


➢ When we are done with performing operations on the file, we need to properly close the file.
➢ Closing a file will free up the resources that were tied with the file. It is done using the close(
) method available in Python.
➢ Python has a garbage collector to clean up unreferenced objects but we must not rely on it to
close the file.

f = open("test.txt", encoding = 'utf-8')


# perform file operations
f.close( )

This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block.

try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close( )

Writing to Files in Python


➢ In order to write into a file in Python, we need to open it in write w, append a or exclusive
creation x mode.
➢ We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to
this, all the previous data are erased.
➢ Writing a string or sequence of bytes(for binaryfiles) is done using the write( ) method. This
method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")

This program will create a new file named test.txt in the current directory if it does not exist. If it does
exist, it is overwritten.

Govt. Polytechnic, Arakere, Srirangapatna Page 20


Python Programming

Reading Files in Python


➢ To read a file in Python, we must open the file in reading r mode.
➢ There are various methods available for this purpose. We can use the read(size) method to read in
the size number of data. If the size parameter is not specified, it reads and returns up to the end of
the file.

We can read the text.txt file we wrote in the above section in the following way:
f = open("test.txt",'r',encoding = 'utf-8')
f.read(4) # read the first 4 data
'This'

f.read(4) # read the next 4 data


' is '

f.read( ) # read in the rest till end of file


'my first file\nThis file\ncontains three lines\n'

f.read( ) # further reading returns empty sting


''
We can see that the read( ) method returns a newline as '\n'. Once the end of the file is reached, we
get an empty string on further reading.
We can change current file cursor(position)using the seek( ) method. Similarly, the tell( ) method
returns our current position (in number of bytes).
f.tell( ) # get the current file position
56

f.seek(0) # bring file cursor to initial position


0

print(f.read( )) # read the entire file


This is my first file
This file
contains three lines
We can read a file line-by-line using a for loop. This is both efficient and fast.
for line in f:
... print(line, end = '')
...
This is my first file
This file
contains three lines

Alternatively, we can use the readline( ) method to read individual lines of a file. This method reads a
file till the newline, including the newline character.
f.readline( )
'This is my first file\n'

Govt. Polytechnic, Arakere, Srirangapatna Page 21


Python Programming

f.readline( )
'This file\n'

f.readline( )
'contains three lines\n'

f.readline( )

Python File Methods


There are various methods available with the file object. Some of them have been used in the above
examples.

The complete list of methods in text mode with a brief description:


Method Description

Closes an opened file. It has no effect if the


close( )
file is already closed.

Separates the underlying binary buffer


detach( )
from the TextIOBase and returns it.

Returns an integer number (file descriptor)


fileno( )
of the file.

flush( ) Flushes the write buffer of the file stream.

Returns True if the file stream is


isatty( )
interactive.

Reads at most n characters from the file.


read(n) Reads till end of file if it is negative or
None.

Returns True if the file stream can be read


readable( )
from.

Reads and returns one line from the file.


readline(n=-1)
Reads in at most n bytes if specified.

Reads and returns a list of lines from the


readlines(n=-1) file. Reads in at most n bytes/characters if
specified.

seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in

Govt. Polytechnic, Arakere, Srirangapatna Page 22


Python Programming

reference to from (start, current, end).

Returns True if the file stream supports


seekable( )
random access.

Returns an integer that represents the


tell( )
current position of the file's object.

Resizes the file stream to size bytes. If size


truncate(size=None)
is not specified, resizes to current location.

Returns True if the file stream can be


writable( )
written to.

Writes the string s to the file and returns


write(s)
the number of characters written.

writelines(lines) Writes a list of lines to the file.

Govt. Polytechnic, Arakere, Srirangapatna Page 23


Python Programming

CHAPTER-13
EXCEPTION HANDLING
These errors can be broadly classified into two classes:
1. Syntax errors
2. Logical errors (Exceptions)

Python Syntax Errors


Error caused by not following the proper structure (syntax) of the language is called syntax
error or parsing error.

Example:
if a < 3
print(a)

Output
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax missing :

Python Logical Errors (Exceptions)


Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors.
For instance, they occur when we try to open a file(for reading) that does not exist
(FileNotFoundError), try to divide a number by zero (ZeroDivisionError), or try to import a
module that does not exist (ImportError).

Python Built-in Exceptions


Some of the common built-in exceptions in Python programming along with the error that cause them
are listed below:
Exception Cause of Error

AssertionError Raised when an assert statement fails.

Raised when attribute assignment or reference


AttributeError
fails.

Raised when the input() function hits end-of-file


EOFError
condition.

FloatingPointError Raised when a floating point operation fails.

Govt. Polytechnic, Arakere, Srirangapatna Page 24


Python Programming

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when the index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

Raised when the user hits the interrupt key (Ctrl+C


KeyboardInterrupt
or Delete).

MemoryError Raised when an operation runs out of memory.

Raised when a variable is not found in local or


NameError
global scope.

NotImplementedError Raised by abstract methods.

Raised when system operation causes system


OSError
related error.

Raised when the result of an arithmetic operation is


OverflowError
too large to be represented.

Raised when a weak reference proxy is used to


ReferenceError
access a garbage collected referent.

Raised when an error does not fall under any other


RuntimeError
category.

Raised by next() function to indicate that there is no


StopIteration
further item to be returned by iterator.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

Raised when indentation consists of inconsistent


TabError
tabs and spaces.

SystemError Raised when interpreter detects internal error.

SystemExit Raised by sys.exit() function.

Govt. Polytechnic, Arakere, Srirangapatna Page 25


Python Programming

Raised when a function or operation is applied to


TypeError
an object of incorrect type.

Raised when a reference is made to a local variable


UnboundLocalError in a function or method, but no value has been
bound to that variable.

Raised when a Unicode-related encoding or


UnicodeError
decoding error occurs.

Raised when a Unicode-related error occurs during


UnicodeEncodeError
encoding.

Raised when a Unicode-related error occurs during


UnicodeDecodeError
decoding.

Raised when a Unicode-related error occurs during


UnicodeTranslateError
translating.

Raised when a function gets an argument of correct


ValueError
type but improper value.

Raised when the second operand of division or


ZeroDivisionError
modulo operation is zero.

Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

Govt. Polytechnic, Arakere, Srirangapatna Page 26


Python Programming

Exceptions in Python
Python has many built-in exceptions that are raised when your program encounters an error

When these exceptions occur, the Python interpreter stops the current process and passes it to
the calling process until it is handled. If not handled, the program will crash.

Catching Exceptions in Python


In Python, exceptions can be handled using a try statement.
The critical operation which can raise an exception is placed inside the try clause. The code that
handles the exceptions is written in the except clause.

Exception handling in python


The try-expect statement
If the Python program contains suspicious code that may throw the exception, we must place that
code in the try block. The try block must be followed with the except statement, which contains a
block of code that will be executed if there is some exception in the try block.

Example:
import sys
a=10
b=0
try:
print("a = ",a)
print("b = ",b)
d = a/b
print("d = ",d)
except:
print("Div by Zero error")
Output:
a = 10
b= 0
Div by Zero error

Govt. Polytechnic, Arakere, Srirangapatna Page 27


Python Programming

Catching Specific Exceptions in Python


• In the above example, we did not mention any specific exception in the except clause.
• This is not a good programming practice as it will catch all exceptions and handle every case in the
same way. We can specify which exceptions an except clause should catch.
• A try clause can have any number of except clauses to handle different exceptions, however, only
one will be executed in case an exception occurs.
• We can use a tuple of values to specify multiple exceptions in an except clause. Here is an
example pseudo code.

try:
# do something
pass

except ValueError:
# handle ValueError exception
pass

except (TypeError, ZeroDivisionError):


# handle multiple exceptions
# TypeError and ZeroDivisionError
pass

except:
# handle all other exceptions
pass

Python try with else clause


In some situations, you might want to run a certain block of code if the code block inside try ran
without any errors. For these cases, you can use the optional else keyword with the try statement.
Syntax:
try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

Govt. Polytechnic, Arakere, Srirangapatna Page 28


Python Programming

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = ",c)
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")

Output:
Enter a:10
Enter b:2
a/b = 5.0
Hi I am else block

Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>

Example:
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)

Govt. Polytechnic, Arakere, Srirangapatna Page 29


Python Programming

Output:
Enter a number: 7
Not an even number!

Enter a number: 6
0.16666…

Creating User-defined Exception


Programmers may name their own exceptions by creating a new exception class. Exceptions
need to be derived from the Exception class, either directly or indirectly. Although not mandatory,
most of the exceptions are named as names that end in “Error” similar to the naming of the
standard exceptions in python. For example:

class MyError(Exception):

# Constructor or Initializer
def __init__(self, value):
self.value = value

# __str__ is to print() the value


def __str__(self):
return(repr(self.value))

try:
raise(MyError(3*2))

# Value of Exception is stored in error


except MyError as error:
print('A New Exception occured: ',error.value)

Output:
A New Exception occured: 6

Raising Exceptions
The raise statement allows the programmer to force a specified exception to occur. For example:
raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere

The sole argument to raise indicates the exception to be raised. This must be either an
exception instance or an exception class (a class that derives from Exception). If an exception class is
passed, it will be implicitly instantiated by calling its constructor with no arguments:

Govt. Polytechnic, Arakere, Srirangapatna Page 30


Python Programming

raise ValueError # shorthand for 'raise ValueError()'

try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise

Output:
An exception flew by!
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-bf6ef4926f8c> in <module>
1 try:
----> 2 raise NameError('HiThere')
3 except NameError:
4 print('An exception flew by!')
5 raise

NameError: HiThere

Govt. Polytechnic, Arakere, Srirangapatna Page 31

You might also like