Python Unit IV
Python Unit IV
MCA-PYTHON
UNIT-IV
MODULES
If we need to reuse the code in python then we can define functions , but if we
need to reuse number of functions then we have to go for modules concept. A
module is nothing but a file with extention of .py , which may contains methods ,
variables & also classes. In Python , Every python file itself is known as a
module . Modules of python .py files that concists of python code. Any python
file can be referenced as a [Link] order to use the properties of one module
into another module we use the "import" statement.
These modules are already defined and kept in python software. So when we
install python then automatically these standard modules will install in our
[Link] example,math, calender, os , sys, json , datetime, ....
These modules are defined by users as per their requirement . So here User
defined module is nothing but the .py file which contains methods, variables, and
also [Link] example: [Link], [Link] , [Link](), [Link]
These modules are already defined by some other people and kept in [Link]
we can download and install in our machines by using "pip" (Python Installer
Package ).PIP is a package management system used to install and manage
software packages written in python like pymysql , cx_oracle.In python, modules
are accessed by using "import" [Link] our current file needed to use
the code which is already existed in other files we can import that
file(modules)When python import a module called as "Mymodule" for example ,
the interpreter will first search for a built-in module called [Link] a built-in
module is not found , the python interpretor will then search for a file named
[Link] in a list of directories that it receives from the [Link]
[Link] can import modules in 3 diffrent ways ,
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
1) import <module_name>
import math
print([Link](2,4))
It is not recomended way in real time programs. Because when importing module
name directly then this module contains all members like functions,variables anc
[Link] if we want to use only one member of this module then remaining all
members are loading not good. here every time we need to use module name
when we want to use member of this module. to overcome this problem we can
use another way of importing.
print(pow(2,4)) # 16
here we can import all members of required module at a time. we can use these
members directly without module name.
print(pow(2,4)) # 16
here we can directly importing required module name only what we want. we
can use this member directly.
Example:
[Link] file
x = 100
def f1():
print("in f1 of mod1")
def f2():
print("in f2 of mod1")
[Link] file
import [Link]
print(module1.x)
module1.f1()
module1.f2()
print("end")
output:
100
in f1 of mod1
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
in f2 of mod2
end
Note: Whenever we import one module into another module then imported
module file will be generated and stored that file into computer hard disc
[Link] generating the compiled file for python module with out
sharing the .py file of that module, we can import that module into other module.
Example:
[Link]
def add(a,b):
return a+b
def sub(a,b):
return a-b
def abs(a):
if a >= 0:
return a
else:
return (-a)
[Link]
import mod3
sum = [Link](30,20)
print(sum)
sub = [Link](30,20)
print(sub)
pr = [Link](-10)
print(pr)
output:
50
10
10
Renaming a module at the time of importing :
When ever we import a module , to access the properties of that module then
compulsary we have to use [Link] .If we rename a
module at the time of importing, we can access the propterties of that module by
using [Link]
For Example:
We can import the "math" module by using alias name , which is providing all
mathematicl properties
import math as m
Inorder to import the specific properties of one module into another module we
use
from <module_name> import <property_name>
Example:
[Link]
from math import pi,e
print("the value of pi is",pi)
print("the value of e is",e)
Output:
the value of pi is 3.14159265354
FILE HANDLING
here open() method taking file_name as first parameter and required file_mode
assecond [Link] Properties of File Object:Once we opend a file and
we got file object, we can get various details related to that file by using its
properties.
name : Name of opened file
mode : Mode in which the file is opened
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
MODES OF FILE
After executing the open function, it will create a file object with the
specified modes like x.
BY calling the methods on the file object, we can read the data from the
file , we can write into file or update the data of a file.
After performing the operations on the file object we have to close the file
object.
By using close() we can close the file object .
READ DATA:
To read the data from file object , in python we have read(), readline() and
readlines() methods.
Using empty read() method we can read entire file object data from where
a file_pointer is available and it returns in the form of string type object.
file_object = open("[Link]")
print ("file is opened")
print(file_object)
data = file_object.read(10)
print(data)
readline():
Python facilitates to read the file line by line by using a function readline()
method.
The empty readline() method reads the current line of the file from the file
pointer location, i.e., if we use the readline() method two times, then we
can get the first two lines of the file.
It is used to Read the entire single line of file where our file pointer is
available.
Consider the following example which contains a function readline() that
reads the first line of our file "[Link]" containing three lines.
Q) Write a python program to read the first line data from the file ?
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
file_object = open("[Link]")
print ("file is opened")
print(file_object)
data = file_object.readline()
print(data)
readline(count_number)
The readline(int) will reads the given specified number of charecters only
from the file pointer location but not upto end of the line.
If given integer value is more than given file data length then readline(int)
will read the data which is available length in a file.
print([Link]())
print([Link](2))
print([Link]())
print([Link](3))
print([Link]())
seek():
We can use seek() method to move cursor (file pointer) to specified location
[Link](offset, fromwhere) ------>offset represents the number of positions
data="All Students are GOOD"
f=open("[Link]","w")
[Link](data)
with open("[Link]","r+") as f:
text=[Link]()
print(text)
print("The Current Cursor Position: ",[Link]())
[Link](17)
print("The Current Cursor Position: ",[Link]())
[Link]("GEMS!!!")
[Link](0)
text=[Link]()
print("Data After Modification:")
print(text)
DICTIONARY-DATA TYPE
A Python dictionary is a data structure that allows us to easily write very efficient
codePython dictionaries allow us to associate a value to a unique key, and then
to quickly access this value. Dictionaries contains set of key/value pairs which
are enclosed between curly braces separated by comma. Here keys are unique.A
pair of curly braces creates an empty dictionary: { }The main operations on a
dictionary are storing a value with some key andextracting the value with given
[Link] keys are not allowed duplicates but dictionary values are
[Link] can use homogeneous and heterogeneous elements for
both keys [Link] order is not [Link] keys are only
immutable and values are mutable | [Link] will not allow indexing
and [Link] are indexed by keys, which can be any immutable types
likestrings and numbers can always be keys But Tuples can be used as keys if
they contain only strings, numbers, or tuples.
dic1 = {}
print(dic1)
type(dic1)
dic1['a']=10
dic1['b']=20
dic1['c']=30
dic1['a']=10
dic1['a']=50
print(dic1)
2. Creating a dictionary with dict() function:
dic1=dict( [ ( 'a ', 10 ) , ( 'b' , 20 ) , ( 'c' , 30 ) , ( 'd' , 40 ) ] )
print(dic1)
type(dic1)
3. Creating a dictionary with "curly braces" including "key:value" pairs.
dic1={'a':10,'b':20,'c':30,'d':40}
print(dic1)
type(dic1)
Access Data from the Dictionary: We can access data by using keys.
d = {100:'krishna',200:'milky', 300:'Tillu'}
print(d[100])
print(d[300])
If the specified key is not available then we will get KeyError
Update Dictionaries
d[key] = value
If the key is not available then a new entry will be added to the dictionary with
the specified key-value pair if the key is already available then old value will be
replaced with new value.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
d[400]="veena"
print(d)
d[100]="sweety"
print(d)
Output
{100: 'krishna', 200: 'milky’, 300: 'Tillu'}
{100: 'krishna', 200: 'milky', 300: 'Tillu', 400: 'veena'}
{100: 'sweety', 200: 'milky', 300: 'Tillu', 400: 'veena'}
Delete Elements from Dictionary
del d[key]
It deletes entry associated with the specified key.
If the key is not available then we will get KeyError.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
del d[100]
print(d)
del d[400]
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
Output
{100: 'krishna', 200: 'milky', 300: 'Tillu'}
{200: 'milky', 300: 'Tillu'}
KeyError: 400
2) [Link]()
To remove all entries from the dictionary.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
[Link]()
print(d)
Output
{100:"krishna",200:"milky",300:"Tillu"}
{}
del d
To delete total [Link] we cannot access d.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
del d
print(d)
Output
{100:"krishna",200:"milky",300:"Tillu"}
NameError: name 'd' is not defined
update():
The update() method updates the dictionary with the elements from
another dictionary object or from an iterable of key/value pairs.
The current dictionary will be updated with the all key:value pairs
fromanother dictionary.
stuDetails={'Id':100,'Name':'Sai', 'subjects':['SQL Server', 'Oracle','Python']}
stuDetails1={'id':1000,'name':'nani'}
[Link](stuDetails1)
print(stuDetails)
{'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python'], 'id':
1000,'name': 'nani'}
Dictionary functions:
dict():
To create a dictionary
d = dict() =It creates empty dictionary
d = dict({100:"krishna",200:"ravi"}) =====>It creates dictionary with specified
elements
d = dict([(100,"krishna"),(200,"milky"),(300,"Tillu")]) It creates dictionary with
the given list of tuple elements
2) len()
Returns the number of items in the dictionary.
dict1 = {101: 'krishna', 102:'milky'};
dict2 = {1001: 'milky', 1002:'19' ,1003:'Tillu'};
print("Length of dict1",len(dict1))
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
print("Length of dict2",len(dict2))
output:
Length of dict1 2
Length of dict2 3
3) clear():
To remove all elements from the dictionary.
4) get():
To get the value associated with the key
[Link](key)
If the key is available then returns the corresponding value otherwise returns
None
5)[Link](key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns
default
value.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d[100]) #krishna
print(d[400]) # KeyError:400
print([Link](100)) #krishna
print([Link](400)) #None
print([Link](100,"Guest")) #krishna
print([Link](400,"Guest")) #Guest
6) pop():
[Link](key)
It removes the entry associated with the specified key and returns the
corresponding value.
If the specified key is not available then we will get KeyError.
d={100:"krishna",200:"milky",300:"Tillu"}
print([Link](100))
print(d)
print([Link](400))
Output
krishna
{200: 'milky', 300: 'Tillu'}
KeyError: 400
7) popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.
d={100:"durga",200:"milky",300:"Tillu"}
print(d)
print([Link]())
print(d)
Output
{100: 'durga', 200: 'milky', 300: 'Tillu'}
(300, 'Tillu')
{100: 'durga', 200: 'milky'}
If the dictionary is empty then we will get KeyError
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
d={}
print([Link]()) ==>KeyError: 'popitem(): dictionary is empty'
8) keys():
It returns all keys associated eith dictionary.
d={100:"durga",200:"milky",300:"Tillu"}
print([Link]())
for k in [Link]():
print(k)
Output
dict_keys([100, 200, 300])
100
200
300
9) values():
It returns all values associated with the dictionary.
d={100:"durga",200:"milky",300:"Tillu"}
print([Link]())
for v in [Link]():
print(v)
Output
dict_values(['durga', 'milky', 'Tillu'])
durga
milky
Tillu
10) items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
d={100:"durga",200:"milky",300:"Tillu”}
for k,v in [Link]():
print(k,"--",v)
Output
100 -- durga
200 -- milky
300 -- Tillu
Q)Merging two Dictionaries into a New Dictionary using ** symbol OR
Create a Python program to merging two dictionaries
dict_3 = dict_2.copy()
dict_3.update(dict_1)
print(dict_3)
OR
d1 = {1:10, 2:20}
d2 = {2:100, 3:30}
d3 = {**d1, **d2}
d3
{1: 10, 2: 100, 3: 30}
Explanation :
This is generally considered a trick in Python where a single expression is
used to merge two dictionaries and stored in a third dictionary.
The single expression is **. This does not affect the other two dictionaries.
** implies that an argument is a dictionary. Using ** [double star] is a
shortcut that allows you to pass multiple arguments to a function directly
using a dictionary.
For more information refer **kwargs in Python. Using this we first pass all
the elements of the first dictionary into the third one and then pass the
second dictionary into the third. This will replace the duplicate keys of the
first dictionary.
Q)Discuss the following methods on dictionary i) index() ii) sorted() iii)
max()
A dictionary is a data structure that consists of key and value pairs. We can sort
a dictionary using two criterias
Sort by key : The dictionary is sorted in ascending order of its keys. The values
are not taken care of.
Sort by value : The dictionary is sorted in ascending order of the values.
Sort the dictionary by key
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2={}
for i in sorted(dic):
dic2[i]=dic[i]
print(dic2)
output: {1: 100, 2: 90, 3: 5, 5: 67, 8: 3}
Sort dictionary by values
============================
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2=dict(sorted([Link](),key= lambda x:x[1]))
print(dic2)
Output:
{8: 3, 3: 5, 5: 67, 2: 90, 1: 100}
The index() method in Python dictionaries is used to find the index or position of
a specified key within the dictionary. index() in dictionaries is not a direct
method available.
Key-Value Pairs: A dictionary in Python consists of key-value pairs. Each key is
unique and associated with a value.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
Accessing Values: You can access the value associated with a key using square
brackets [].
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['b'])
The max() function in Python is used to find the maximum value among the keys
of a dictionary. It can also accept a key function similar to sorted() to find the
maximum based on values rather than keys.
my_dict = {'c': 3, 'a': 1, 'b': 2}
max_key = max(my_dict)
print(max_key) # Output: 'c'
Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.
squares={x:x*x for x in range(1,6)}
print(squares)
doubles={x:2*x for x in range(1,6)}
print(doubles)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
Q ) How to perform arithmetic operations on the values of a dictionary?
d1={'sub1':80,'sub2':90,'sub3':70,'sub4':80}
print(d1)
{'sub1': 80, 'sub2': 90, 'sub3': 70, 'sub4': 80}
s = sum([Link]())
print(s) 320
mx = max([Link]())
print(mx) 90
mn = min([Link]())
print(mn) 70
cnt = len([Link]())
print(cnt) 4
Quotations in Python:
Python accepts single ('), double (") and triple (''' or """) quotes to denote
string literals, as long as the same type of quote starts and ends the
string.
Generally triple quotes are used to write the string across multiple lines.
For example1 :
word = 'word'
sentence = "This is a sentence."
Paragraph = """This is a paragraph. It is
made up of multiple lines and sentences.""
Accessing Characters By using Index:
Python supports both +ve and -ve Index.
s = 'krishna'
print(len(s))
Checking Membership:
We can check whether the character or string is the member of another string or
not by
using in and not in operators
s = input("Enter main string:")
subs = input("Enter sub string:")
if subs in s:
print(subs,"is found in main string")
else:
print(subs,"is not found in main string")
Comparison of Strings:
We can use comparison operators (<, <=, >, >=) and equality operators (==, !
=) for
strings. Comparison will be performed based on alphabetical order.
Example: develop a python program to find substring within a given string?
s1=input("Enter first string:")
2s2=input("Enter Second string:")
if s1==s2:
print("Both strings are equal")
elif s1<s2:
print("First String is less than Second String")
else:
print("First String is greater than Second String")
find():
syntax: [Link](substring)
Returns index of first occurrence of the given substring. If it is not available then
we will
get -1.
s="Learning Python is very easy"
print([Link]("Python")) #9
print([Link]("Java")) # -1
print([Link]("r"))#3
print([Link]("r"))#21
Note: By default find() method can search total string. We can also specify the
boundaries to search.
[Link](substring,bEgin,end)
It will always search from bEgin index to end-1 index.
s="durgaravipavanshiva"
print([Link]('a'))#4
print([Link]('a',7,15))#10
print([Link]('z',7,15))#-1
Counting substring in the given String:
We can find the number of occurrences of substring present in the given string
by using
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
count() method.
1) [Link](substring) : It will search through out the string.
2) [Link](substring, begin, end) : It will search from bEgin index to end-1
index.
s="abcabcabcabcadda"
print([Link]('a'))
print([Link]('ab'))
print([Link]('a',3,7))
Replacing a String with another String:
Syntax: [Link](oldstring, newstring)
inside s, every occurrence of old String will be replaced with new String.
s = "Learning Python is very difficult"
s1 = [Link]("difficult","easy")
print(s1)
Output: Learning Python is very easy
Splitting of Strings:
We can split the given string according to specified seperator by using split()
method.
l = [Link](seperator)
The default seperator is space. The return type of split() method is List.
s="krishna software solutions"
l=[Link]()
for x in l:
print(x)
Output:
krishna
software
solutions
Joining of Strings:
We can join a Group of Strings (List OR Tuple) wrt the given Seperator.
s = [Link](group of strings)
Eg 1:
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s)
Output: sunny-bunny-chinny
Eg 2:
l = ['hyderabad', 'singapore', 'london', 'dubai']
s = ':'.join(l)
print(s)
Output: hyderabad:singapore:london:dubai
Changing Case of a String:
We can change case of a string by using the following 4 methods.
1) upper() :To convert all characters to upper case
2) lower() :To convert all characters to lower case
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
3) swapcase() :Converts all lower case characters to upper case and all upper
case
characters to lower case
4) title() : To convert all character to title case. i.e first character in every word
should
be upper case and all remaining characters should be in lower case.
5) capitalize() :Only first character will be converted to upper case and all
remaining
characters can be converted to lower case
s = 'learning Python is very Easy'
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
Checking Starting and Ending Part of the String:
Python contains the following methods for this purpose
1) [Link](substring)
2) [Link](substring)
s = 'learning Python is very easy'
print([Link]('learning'))
print([Link]('learning'))
print([Link]('easy'))
To Check Type of Characters Present in a String:
Python contains the following methods for this purpose.
1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0
to9 )
2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to
Z)
3) isdigit(): Returns True if all characters are digits only( 0 to 9)
4) islower(): Returns True if all characters are lower case alphabet symbols
5) isupper(): Returns True if all characters are upper case aplhabet symbols
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces
s=input("Enter any character:")
if [Link]():
print("Alpha Numeric Character")
if [Link]():
print("Alphabet character")
if [Link]():
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
pop():
We can also use the pop() method to remove the item. Generally, the pop()
method will always remove the last item but the set is unordered, we can't
determine which element will be popped out from set.
s1 = {90,40, 10, 20, 30}
[Link]()
40
[Link]()
10
Assignment operator
By using assignment operator, if we assigning given set object in to another
object then both can share the same memory address.
set1 = {1, 2, 3, 4, 5}
set2 = set1
set1
{1, 2, 3, 4, 5}
set2
{1, 2, 3, 4, 5}
id(set1)
2693878076136
id(set3)
2693878076136
copy():
This function copies the elements of one set to another new set and also it
creates new memory value.
copy() method always creates new memory for new set object. so both
memories are different but values are same.
set1={1,2,3,4,5}
set2=[Link]() #copying se1 elements to se2
set1 {1, 2, 3, 4, 5}
set2 {1, 2, 3, 4, 5} # id values different.
id(set1)
2693878076136
id(set2)
2693878076360
clear():
By using clear() function we can clear or remove all elements from the given set
object.
se1={1,2,3,4,5}
print(se1) {1, 2, 3, 4, 5}
type(se1) <class 'set'>
[Link]() #clearing the se1, so se1 will become empty set.
print(se1) set()
Python Set Operations:
Set can be performed mathematical operation such as union, intersection,
difference, and symmetric difference. Python provides the facility to carry out
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
se1={1,2,3,4,5}
se2={1,2,3,6,7}
[Link](se2) {1, 2, 3, 4, 5, 6, 7} or
se1|se2 {1, 2, 3, 4, 5, 6, 7}
Or
[Link](se1) {1, 2, 3, 4, 5, 6, 7}
se2|se1 {1, 2, 3, 4, 5, 6, 7}
intersection():
It returns an intersection elements of two sets, that means it returns only
common elements from both [Link] same operation we can get by sing ‘&’
operator.
Syntax: <First_Set>.intersection(<Second_Set>) or <First_Set> &
<Second_Set>
se1={1,2,3,4,5}
se2={1,2,3,6,7}
[Link](se2) {1, 2, 3} or
se1&se2 {1, 2, 3}
Or
[Link](se1) {1, 2, 3}
se2&se1 {1, 2, 3}
diffferenece():
It returns all elements from first set which are not there in the second set.
Syntax: <First_set>.difference(<Secnd_Set>) or <First_Set> -
<Second_Set>
se1={1,2,3,4,5}
se2={1,2,3,6,7}
[Link](se2) {4, 5} or
se1-se2 {4, 5}
Or
[Link](se1) {6, 7} or
se2-se1 {6, 7}
intersection_update():
The intersection_update() method removes the items from the original set
that are not present in both the sets (all the sets if more than one are
specified).
The intersection_update() method is different from the intersection()
method since it modifies the original set by removing the unwanted items,
on the other hand, the intersection() method returns a new set.
Syntax: <First_Set>.intersection_update(<Second_Set>)
se1={1,2,3,4,5}
se2={1,2,3,6,7}
se1.intersection_update(se2)
print(se1) {1, 2, 3}
print(se2) {1, 2, 3, 6, 7}
differenece_update():
The result of difference between two sets will in First_Set.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
Syntax: <First_Set>.difference_update(<Second_Set>)
se1={1,2,3,4,5}
se2={1,2,3,6,7}
se1.difference_update(se2)
print(se1)
print(se2)
The list and tuple can be created by using the elements without any
defining the key whereas the dictionary uses the key and value pairs.
If we want to create a group of elements with some key name, then we
can go for dictionary as it accepts key and value.
When we want to list out few elements and want to make changes later as
per our requirement we can go for list.
When we want to combine few elements into group and don’t want to
apply any changes further then we can go for tuple. Let’s see the
combined example of the list, tuple and the dictionary.
Exception Handling
Exception definition :An exception is an event, which occurs during the
excution of a program,that disrupts the normal flow of the program instructions
We can handle the exceptions at runtime. But we cannot handle
[Link] are related to application, where as errors are related to
environment in which the application is [Link] error is a term which is used
to describe any issue that arisesunexpectedly that cause a computer do not
functioning properly.
Debugging: The process of finding and eliminating the errors is called
Debugging. In Python We have 2 types of Errors:
1 ) SyntaxError
2 ) RuntimeError
1 Syntax error :
The errors which occurs because of "invalid syntax" are known as "Syntax
errors". Interpreter will check for syntax errors when ever we run the python
program
If syntax error is found , Then no byte code is generating.
With out byte code, program excution is not possible.
Developers only responsible to solve these errors.
def m1():
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
print('Hi')
Example1:
def m1():
print('Hi')
Output : SyntaxError : Expected an indented block
2) RUNTIME ERRORS :
The errors which occurs at the time of excution of a program are known as
runtime errors.
We get Runtime Errors because of programing logic, invalid input,memory
related issues etc...
For every RuntimeError , Python is providing corresponding exception
class is available.
Example1: KeyError , IndexError, ValueError, NameError etc ....
At the time of execution of a program if any Runtime Error is occur then
internally corresponding Runtime Error representation classes object will
be created
What is Exception
An unwanted and unexpected event that disturbs normal flow of program is
called exception.
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
It is highly recommended to handle exceptions. The main objective of exception
handling
is Graceful Termination of the program (i.e we should not block our resources
and we should not miss anything). Exception handling does not mean repairing
exception. We have to define alternative way to continue rest of the program
normally
Default Exception Handing in Python:
Every exception in Python is an object. For every exception type the
corresponding classes are available.
Whevever an exception occurs PVM will create the corresponding
exception object and will check for handling code. If handling code is not
available then Python interpreter terminates the program abnormally and
prints corresponding exception information to the console.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
Without try-except:
print("stmt-1")
print(10/0)
print("stmt-3")
Output
stmt-1
ZeroDivisionError: division by zero
Abnormal termination/Non-Graceful Termination
With try-except:
print("stmt-1")
try:
print(10/0)
except ZeroDivisionError:
print(10/2)
print("stmt-3")
Output
stmt-1
5.0
stmt-3
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
except ValueError:
print("please provide int value only")
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: 2
5.0
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: ten
please provide int value only
If try with multiple except blocks available then the order of these except blocks
is important .Python interpreter will always consider from top to bottom until
matched except block identified.
Single except Block that can handle Multiple Exceptions:
We can write a single except block that can handle multiple different types of
exceptions.
except (Exception1,Exception2,exception3,..): OR
except (Exception1,Exception2,exception3,..) as msg :
Parentheses are mandatory and this group of exceptions internally considered as
tuple.
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except (ZeroDivisionError,ValueError) as msg:
print("Plz Provide valid numbers only and problem is: ",msg)
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: 0
Plz Provide valid numbers only and problem is: division by zero
finally Block:
☕ It is not recommended to maintain clean up code(Resource Deallocating Code
or Resource Releasing code) inside try block because there is no guarentee for
the execution of every statement inside try block always.
☕ It is not recommended to maintain clean up code inside except block, because
if there
is no exception then except block won't be executed.
☕ Hence we required some place to maintain clean up code which should be
executed always irrespective of whether exception raised or not raised and
whether exception handled or not handled. Such type of best place is nothing
but finally block.
☕ Hence the main purpose of finally block is to maintain clean up code
ANNAMACHARYA UNIVERSITY
MCA-PYTHON
Syntax:
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
The speciality of finally block is it will be executed always whether exception
raised or not
raised and whether exception handled or not handled.
Case-1: If there is no exception
try:
print("try")
except:
print("except")
finally:
print("finally")
Output
try
finally
Case-2: If there is an exception raised but handled
try:
print("try")
print(10/0)
except ZeroDivisionError:
print("except")
finally:
print("finally")
Output
try
except
finally
Types of Exceptions:
print(10/0)
Eg:
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException
PROGRAMS: