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

Python Unit 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Unit 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Python Programming

Unit 3
Janhavi Vadke
Topics
• Lists:
• Tuples and Dictionaries:
• Files:
• Exceptions:
Lists
• The list is a most versatile datatype available in Python
which can be written as a list of comma-separated
values (items) between square brackets.
• Important thing about a list is that items in a list need
not be of the same type.
• e.g :
• list1 = ['physics', 'chemistry', 1997, 2000]
• list2 = [1, 2, 3, 4, 5 ]
• list3 = ["a", "b", "c", "d"]
• list indices start at 0, and lists can be sliced,
concatenated and so on.
Accessing value
• To access values in lists, use the square
brackets for slicing along with the index or
indices to obtain value available at that
index
• Index starts with 0.
• Last element has index -1.
• print(List1[0])
• print(List1[-1])
• list1 = ['physics', 'chemistry', 1997, 2000]
• list2 = [1, 2, 3, 4, 5, 6, 7 ]
• print ("list1[0]: ", list1[0])
• print ("list2[1:5]: ", list2[1:5])
• o/p
• list1[0]: physics
• list2[1:5]: [2, 3, 4, 5]
Lists are Mutable
• List are mutable, meaning, their elements can be
changed unlike string or tuple
• We can update single or multiple elements of lists by
giving the slice on the left-hand side of the assignment
operator.
• list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : “)
print (list[2])
list[2] = 2001
print ("New value available at index 2 : " )
print (list[2])
• We can add one item to a list using append() method or
add several items using extend() method.
• odd = [1, 3, 5]
1)odd.append(7)
• print(odd) # Output: [1, 3, 5, 7]
2)odd.extend([9, 11, 13])
• print(odd) # Output: [1, 3, 5, 7, 9, 11, 13]
• Furthermore, we can insert one item at a desired location
by using the method insert()
• odd = [1, 9]
3)odd.insert(1,3)
• print(odd) # Output: [1, 3, 9]
Traversing a List
• Using a for loop we can iterate though each
item in a list.
• for fruit in ['apple','banana','mango']:
print("I like",fruit)
Delete List Elements
• To remove a list element, you can use either
the del statement if you know exactly which
element(s) you are deleting
• list1 = ['physics', 'chemistry', 1997, 2000]
• print (list1)
• del list1[2]
• print "After deleting value at index 2 : "
• print (list1)
• We can use remove() method to remove the
given item if exact element is not known.
• my_list = ['p','r','o','b','l','e','m']
• my_list.remove('p')
• print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm']
• my_list.clear()
• print(my_list) # Output: []
Built in List Operators
• Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a
new list, not a string.
• >>> a = [1, 2, 3]
• >>> b = [4, 5, 6]
• >>> c = a + b
• >>> print c
• [1, 2, 3, 4, 5, 6]
• The * operator repeats a list a given number of times:
• >>> [0] * 4
• [0, 0, 0, 0]
• >>> [1, 2, 3] * 3
• [1, 2, 3, 1, 2, 3, 1, 2, 3]
List Membership Test
• We can test if an item exists in a list or not, using
the keyword in.
• my_list = ['p','r','o','b','l','e','m']
• print('p' in my_list)
• # Output: True
• print('a' in my_list)
• # Output: False
• print('c' not in my_list)
• # Output: True
Built in List Methods
• append() - Add an element to the end of the list
• extend() - Add all elements of a list to the another list
• insert() - Insert an item at the defined index
• remove() - Removes an item from the list
• pop() - Removes and returns an element at the given index
• clear() - Removes all items from the list
• index() - Returns the index of the first matched item
• count() - Returns the number of times the value appears int
the list
• sort() - Sort items in a list in ascending order
• reverse() - Reverse the order of items in the list
• copy() - Returns a shallow copy of the list
Built-in Functions
• Built-in functions like all(), any(), enumerate(),
len(), max(), min(), list(), sorted() etc. are
commonly used with list to perform different
tasks.
Function Description

Return the length (the number of items) in the


len()
list.
Convert an iterable (tuple, string, set,
list()
dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list
Return a new sorted list (does not sort the list
sorted()
itself).
sum() Return the sum of all elements in the list.
Tuples
• A tuple is a sequence of immutable Python
objects. Tuples are sequences, just like lists.
• The differences between tuples and lists are, the
tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square
brackets.
• tup1 = ('physics', 'chemistry', 1997, 2000)
• tup2 = (1, 2, 3, 4, 5 )
• tup3 = ("a", "b", "c", "d“)
• Tuple indices start at 0, and they can be sliced,
concatenated, and so on.
• To create a tuple with a single element, you have to include
a final comma:
• >>> t1 = 'a',
• >>> type(t1)
• <type 'tuple'>
• Another way to create a tuple is the built-in function tuple.
With no argument, it creates an empty tuple:
• >>> t = tuple()
• >>> print (t)
• ()
• If the argument is a sequence (string, list or
tuple), the result is a tuple with the elements
of the sequence:
• >>> t = tuple('lupins')
• >>> print (t)
• ('l', 'u', 'p', 'i', 'n', 's')
Accessing values in Tuples
• To access values in tuple, use the square
brackets for slicing along with the index or
indices to obtain value available at that index.
• tup1 = ('physics', 'chemistry', 1997, 2000)
• tup2 = (1, 2, 3, 4, 5, 6, 7 )
• print ("tup1[0]: ", tup1[0])
• print ("tup2[1:5]: ", tup2[1:5])
• Tuples are immutable which means we cannot
update or change the values of tuple elements
• tup1 = (12, 34.56)
• tup2 = ('abc', 'xyz')
• # Following action is not valid for tuples
• # tup1[0] = 100
• # So let's create a new tuple as follows
• tup3 = tup1 + tup2
• print (tup3)
Tuple Assignment
• >>> a,b = 3,4
• >>> print (a) #3
• >>> print (b) #4
• >>> a,b,c = (1,2,3),5,6
• >>> print (a) #(1, 2, 3)
• >>> print (b) #5
• >>> print (c) #6
• The left side is a tuple of variables; the right side is a tuple
of expressions. Each value is assigned to its respective
variable. All the expressions on the right side are
evaluated before any of the assignments.
• The number of variables on the left and the number of
values on the right have to be the same:
• >>> a, b = 1, 2, 3 #wrong
• >>> addr = '[email protected]'
• >>> uname, domain = addr.split('@')
• The return value from split is a list with two
elements; the first element is assigned to uname,
the second to domain.
• >>> print (uname)
• monty
• >>> print (domain)
• python.org
Tuples as return values
• A function can only return one value, but if the
value is a tuple, the effect is the same as
returning multiple values.
• The built-in function divmod takes two
arguments and returns a tuple of two values, the
quotient and remainder. You can store the result as
a tuple:
• >>> t = divmod(7, 3)
• >>> print (t)
• (2, 1)
• Or use tuple assignment to store the elements
separately:
• >>> quot, rem = divmod(7, 3)
• >>> print quot
• 2
• >>> print rem
• 1
Variable-length argument tuples
• Functions can take a variable number of arguments. A
parameter name that begins with * gathers arguments
into a tuple. For example, printall takes any number of
arguments and prints them:
• def printall(*args):
• print args
• The gather parameter can have any name you like, but
args is conventional. Here’s how the function works:
• >>> printall(1, 2.0, '3')
• (1, 2.0, '3')
• The complement of gather is scatter. If you
have a sequence of values and you want to
pass it to a function as multiple arguments,
you can use the * operator.
• For example,
• def sum(a, b, c, d, e):
• print ( a + b + c + d + e )
• args = (10, 20, 30, 40, 50)
• sum(*args)
Basic tuples operations
• my_tuple = ('p','r','o','g','r','a','m','i','z')
• print(my_tuple[1:4])
• # elements 2nd to 4th---Output: ('r', 'o', 'g')
• print(my_tuple[:-7])
• # elements beginning to 2nd--- Output: ('p', 'r')
• print(my_tuple[7:])
• # elements 8th to end---- Output: ('i', 'z')
• print(my_tuple[:])
• # elements beginning to end--- Output: ('p',
'r’,'o','g','r','a','m','i','z')
Concatenation, Repetition, In Operator,
Iteration
• Tuples respond to the + and * operators much like
strings; they mean concatenation and repetition
here too, except that the result is a new tuple, not
• Python Expression Results Description
• len((1, 2, 3)) 3 Length
• (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
• ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
• 3 in (1, 2, 3) True Membership
• for x in (1,2,3) : print (x, end=' ') 1 2 3 Iteration
Built-in Tuple Functions
1 ) cmp(tuple1, tuple2)
• No longer available in Python 3.
2 ) len(tuple)
• Gives the total length of the tuple.
3 ) max(tuple)
• Returns item from the tuple with max value.
4 ) min(tuple)
• Returns item from the tuple with min value.
5 ) tuple(seq)
• Converts a list into tuple.
Method Description

Python Tuple count() returns occurrences of element in a tuple

Python Tuple index() returns smallest index of element in tuple

Python len() Returns Length of an Object

Python max() returns largest element

Python min() returns smallest element

Python reversed() returns reversed iterator of a sequence

Python sorted() returns sorted list from a given iterable

Python sum() Add items of an Iterable

Python tuple() Function Creates a Tuple


Creating a Dictionary
• Each key is separated from its value by a colon (:),
the items are separated by commas, and the
whole thing is enclosed in curly braces. An empty
dictionary without any items is written with just
two curly braces, like this: {}.
• Keys are unique within a dictionary while values
may not be.
• The values of a dictionary can be of any type, but
the keys must be of an immutable data type such
as strings, numbers, or tuples
Accessing Values in a dictionary
• To access dictionary elements, you can use the
familiar square brackets along with the key to
obtain its value.
• dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
• print ("dict['Name']: ", dict['Name'])
• print ("dict['Age']: ", dict['Age'])
Lookup
• Given a dictionary d and a key k, it is easy to find
the corresponding value v = d[k].
This operation is called a lookup.
• But what if you have v and you want to find k?
You have two problems:
1) there might be more than one key that maps to
the value v. Depending on the application, you
might be able to pick one, or you might have to
make a list that contains all of them.
2)There is no simple syntax to do a reverse lookup;
you have to search.
• d1={1:'a', 2:'b', 3:'c'}
• for x in d1:
• print(x, d1[x])
• def reverse_lookup(d, v):
• for k in d:
• if d[k] == v:
• return k
• k1 = reverse_lookup(d1, 'b')
• print(k1)
Example
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
h = histogram(‘parrot')
print(h)
Cont.. Example
Looping and dictionaries
def print_hist(h):
for c in h:
print (c, h[c])
h = histogram('parrot')
print_hist(h)
Cont.. Example
Reverse lookup
• def reverse_lookup(d, v):
for k in d:
if d[k] == v:
return k
raise ValueError
• h = histogram('parrot')
• k = reverse_lookup(h, 2)
• print (k)
Updating Dictionary
• You can update a dictionary by adding a new
entry or a key-value pair, modifying an existing
entry, or deleting an existing entry.
• dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry
• print ("dict['Age']: ", dict['Age'])
• print ("dict['School']: ", dict['School'])
Deleting Elements from Dictionary
• We can either remove individual dictionary elements
or clear the entire contents of a dictionary. We can also
delete entire dictionary in a single operation.
• To explicitly remove an entire dictionary, just use the
del statement.
• dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
• del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict
• del dict # delete entire dictionary
• print ("dict['Age']: ", dict['Age'])
• print ("dict['School']: ", dict['School'])
Operations in Dictionary
• >>>eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
• >>>print (eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
• >>>print eng2sp['two']
'dos‘
• >>> len(eng2sp)
3
• >>> 'one' in eng2sp
• True
• >>> 'uno' in eng2sp
• False
• >>> vals = eng2sp.values()
• >>> 'uno' in vals
• True
Properties of Dictionary keys
• Dictionary values have no restrictions. They can be any
arbitrary Python object, either standard objects or user-
defined objects.
• There are two important points to remember about
dictionary keys-
1) More than one entry per key is not allowed. This means
no duplicate key is allowed.
• dict = {'Name': 'Zara', 'Age': 7, 'Name': ‘Seema'}
• print ("dict['Name']: ", dict['Name'])
2) Keys must be immutable. This means you can use strings,
numbers or tuples as dictionary keys
• dict = {['Name']: 'Zara', 'Age': 7}
• print ("dict['Name']: ", dict['Name'])
Built-In Dictionary Functions
1) cmp(dict1, dict2)
No longer available in Python 3.
2) len(dict)
Gives the total length of the dictionary. This would be
equal to the number of items in the dictionary.
3) str(dict)
Produces a printable string representation of a dictionary.
4) type(variable)
Returns the type of the passed variable. If passed variable
is dictionary, then it would return a dictionary type.
Built-in Dictionary Methods
1) dict.clear()
• Removes all elements of dictionary dict.
2) dict.copy()
• Returns a shallow copy of dictionary dict.
3) dict.fromkeys()
• Create a new dictionary with keys from seq and
values set to value.
4) dict.get(key, default=None)
• For key key, returns value or default if key not in
dictionary.
6) dict.items()
• Returns a list of dict's (key, value) tuple pairs.
7) dict.keys()
• Returns list of dictionary dict's keys.

9) dict.update(dict2)
• Adds dictionary dict2's key-values pairs to dict.
10) dict.values()
• Returns list of dictionary dict's values.
Python len() Returns Length of an Object

Python max() returns largest element

Python min() returns smallest element

returns sorted list from a given


Python sorted()
iterable

Python sum() Add items of an Iterable

Returns & Removes Element


Python Dictionary popitem()
From Dictionary

removes and returns element


Python Dictionary pop()
having given key
Files:
• Python provides basic functions and methods
necessary to manipulate files by default. You
can do most of the file manipulation using a
file object.
Text Files
• The open() Function
• Before we can read or write a file, we have to open it using
Python's built-in open() function. This function creates a file
object, which would be utilized to call other support methods
associated with it.
• file object = open(file_name [, access_mode][, buffering])
• file_name: The file_name argument is a string value that contains
the name of the file that you want to access.
• access_mode: The access_mode determines the mode in which
the file has to be opened, i.e., read, write, append, etc.
• buffering: If the buffering value is set to 0, no buffering takes
place. If the buffering value is 1, line buffering is performed while
accessing a file.
• Modes Description
• r Opens a file for reading only. The file pointer is
placed at the beginning of the file. This is the
default mode.
• rb Opens a file for reading only in binary format.
The file pointer is placed at the beginning of the
file. This is the default mode.
• r+ Opens a file for both reading and writing. The
file pointer placed at the beginning of the file.
• rb+ Opens a file for both reading and writing
in binary format. The file pointer placed at the
beginning of the file.
• w Opens a file for writing only. Overwrites the file if the
file exists. If the file does not exist, creates a new file for
writing.
• wb Opens a file for writing only in binary format.
Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
• w+ Opens a file for both writing and reading. Overwrites
the existing file if the file exists. If the file does not exist,
creates a new file for reading andwriting.
• wb+ Opens a file for both writing and reading in
binary format. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and
writing.
• a Opens a file for appending. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file
does not exist, it creates a new file for writing.
• ab Opens a file for appending in binary format. The file pointer is
at the end of the file if the file exists. That is, the file is in the
append mode. If the file does not exist, it creates a new file for
writing.
• a+ Opens a file for both appending and reading. The file pointer is
at the end of the
• file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading andwriting.
• ab+ Opens a file for both appending and reading in binary format.
The filepointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
The File Object Attributes
• Attribute Description
• file.closed Returns true if file is closed,
false otherwise.
• file.mode Returns access mode with
which file was opened.
• file.name Returns name of the file.
• fo = open("foo.txt", "wb")
• print ("Name of the file: ", fo.name)
• print ("Closed or not : ", fo.closed)
• print ("Opening mode : ", fo.mode)
• fo.close()
The close() Method
• The close() method of a file object flushes any
unwritten information and closes the file
object, after which no more writing can be
done.
• fo = open("foo.txt", "w")
• print ("Name of the file: ", fo.name)
• fo.close()
The write() Method
• The write() method writes any string to an
open file.
• The write() method does not add a newline
character ('\n') to the end of the string-.
• fo = open("foo.txt", "w")
• fo.write( "Python is a great language.\nYeah
its great!!\n")
• fo.close()
The read() Method
• The read() method reads a string from an open
file. It is important to note that Python strings can
have binary data apart from text data.
• fileObject.read([count]);
• Here, passed parameter is the number of bytes to
be read from the opened file. This method starts
reading from the beginning of the file and if count
is missing, then it tries to read as much as
possible, maybe until the end of file.
• fo = open("foo.txt", "r+")
• str = fo.read(10)
• print ("Read String is : ", str)
• fo.close()
File Positions
• The tell() method tells you the current position within the
file; in other words, the next read or write will occur at that
many bytes from the beginning of the file.
• The seek(offset[, from]) method changes the current file
position. The offset argument indicates the number of
bytes to be moved. The from argument specifies the
reference position from where the bytes are to be moved.
• If from is set to 0, the beginning of the file is used as the
reference position. If it is set to 1, the current position is
used as the reference position. If it is set to 2 then the end
of the file would be taken as the reference position.
• fo = open("foo.txt", "r+")
• str = fo.read(10)
• print ("Read String is : ", str)
• position = fo.tell()
• print ("Current file position : ", position)
• position = fo.seek(0, 0)
• str = fo.read(10)
• print ("Again read String is : ", str)
• fo.close()
Directories
• Renaming and Deleting Files
• Python os module provides methods that help
you perform file-processing operations, such
as renaming and deleting files.
• To use this module, you need to import it first
• The rename() Method
• The rename() method takes two arguments, the current
filename and the new filename.
• os.rename(current_file_name, new_file_name)
• import os
• os.rename( "test1.txt", "test2.txt" )
• The remove() Method
• You can use the remove() method to delete files by supplying
the name of the file to be deleted as the argument
• os.remove(file_name)
• import os
• os.remove("text2.txt")
• The mkdir() Method
• You can use the mkdir() method of the os module to create
directories in the current directory. You need to supply an
argument to this method, which contains the name of the
directory to be created.
• os.mkdir("newdir")
• import os
• os.mkdir("test")
• The chdir() Method
• The chdir() method takes an argument, which is the name of the
directory that you want tomake the current directory.
• os.chdir("newdir")
• import os
• os.chdir("/home/newdir")
• The getcwd() Method
• The getcwd() method displays the current working
directory.
• os.getcwd()
• The rmdir() Method
• The rmdir() method deletes the directory, which is
passed as an argument in the method. Before
removing a directory, all the contents in it should
beremoved.
• import os
• os.rmdir( "/tmp/test" )
Built-in Exceptions
• An exception is an event, which occurs during the
execution of a program that disrupts the normal
flow of the program's instructions. In general,
when a Python script encounters a situation that
it cannot cope with, it raises an exception. An
exception is a Python object that represents an
error.
• When a Python script raises an exception, it must
either handle the exception immediately
otherwise it terminates and quits.
EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions

StopIteration Raised when the next() method of an iterator does not point to any object.

SystemExit Raised by the sys.exit() function.

StandardError Base class for all built-in exceptions except StopIteration and SystemExit.

ArithmeticError Base class for all errors that occur for numeric calculation.

OverflowError Raised when a calculation exceeds maximum limit for a numeric type.

FloatingPointError Raised when a floating point calculation fails.

ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.

AssertionError Raised in case of failure of the Assert statement.

AttributeError Raised in case of failure of attribute reference or assignment.

EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.

ImportError Raised when an import statement fails.

KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.

LookupError Base class for all lookup errors.

IndexError Raised when an index is not found in a sequence.


KeyError Raised when the specified key is not found in the dictionary.

NameError Raised when an identifier is not found in the local or global namespace.

UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.

IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
IOError Raised for operating system-related errors.

SyntaxError Raised when there is an error in Python syntax.


IndentationError Raised when indentation is not specified properly.

SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.

SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.

TypeError Raised when an operation or function is attempted that is invalid for the specified data type.

ValueError Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.

RuntimeError Raised when a generated error does not fall into any category.

NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.
Handling an exception
• If you have some suspicious code that may
raise an exception, you can defend your
program by placing the suspicious code in a
try: block.
• After the try: block, include an except:
statement, followed by a block of code which
handles the problem as elegantly as possible.
• A single try statement can have multiple except
statements. This is useful when the try block
contains statements that may throw different
types of exceptions.
• You can also provide a generic except clause,
which handles any exception.
• After the except clause(s), you can include an
else-clause. The code in the else-block executes
if the code in the try: block does not raise an
exception.
• The else-block is a good place for code that
does not need the try: block's protection.
• 1) try-----except
try:
num=int(input("Enter the number"))
re=100/num
except(ZeroDivisionError):
print("please enter non zero value")
else:
print("Result is : ",re)
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()

This example if open in read mode where we do not have


the write permission, so it will raise an exception-
2) Except with multiple Exceptions
try:
num=int(input("Enter the number"))
re=100/num
except(ValueError, ZeroDivisionError):
print("please enter non zero integer")
else:
print("Result is : ",re)
3) try-----exceptI, exceptII….
try: You do your operations here;
......................
except ExceptionI: If there is ExceptionI, then
execute this block.
except ExceptionII: If there is ExceptionII, then
execute this block. ......................
else: If there is no exception then execute this
block.
try:
num=int(input("enter the no"))
re=100/num
except ValueError:
print("value is not int type")
except ZeroDivisionError:
print("Don't use zero")
else:
print("result is",re)
4) Except with no exceptions
All types of exceptions that occur are caught by
the try-except statement.
try:
num=int(input("Enter the number"))
re=100/num
except:
print("please enter valid data")
else:
print("Result is : ",re)
5) try----finally
Optional finally clause will be executed by the
interpreter , whether the try statement raises an
exception or not. Else clause can not be used with
finally.
try:
fob = open('test.txt', 'w')
fob.write("It's my test file to verify try-finally ")
print("try block executed")
finally:
fob.close()
print("finally block executed")
Exception with Arguments
• An exception can have an argument, which is a value
that gives additional information about the problem.
The contents of the argument vary by exception. You
capture an exception's argument by supplying a
variable in the except clause as follows-
• try:
• You do your operations here
• ......................
• except ExceptionType as Argument:
• You can print value of Argument here...
• If you write the code to handle a single exception,
you can have a variable follow the name of the
exception in the except statement. If you are
trapping multiple exceptions, you can have a
variable follow the tuple of the exception.
try:
num=int(input("enter the number"))
re=100/num
except Exception as e:
print("Exception:",type(e))
User-defined Exceptions
• Python also allows you to create your own exceptions by deriving
classes from the standard built-in exceptions.
class Error(Exception):
pass
class SmallValueError (Error):
pass

age=int(input("enter the age"))


try:
if age<18:
raise SmallValueError
except SmallValueError:
print("you are less than 18 years, you can not vote")
else:
print("you can vote")

You might also like