Module3 Python Programming
Module3 Python Programming
Module III: Object oriented programming- class, object, method, attribute, destructor,
encapsulation, data hiding; Exception handling- built in exceptions, Handling, Exception with
arguments, Raising and User defined exceptions, Assertions in Python; Regular expressions –
match, search, replace, patterns.
Object Oriented Programming is a powerful method for creating programs. A class is the base
of Object Oriented Programming. A class contains a collection of data (variables) and methods
(functions) that act on those data. Class is considered as a blueprint for an object. For
example consider the design of a house with details of windows, doors, roofs and floors. We
can build the house based on the descriptions. This can be considered as a class while the object
is the house itself. An object is said to be an instance of a class and the process of creating a
class is called instantiation. The basic concepts related to OOP are as follows:
Classes
Objects
Encapsulation
Data Hiding
Inheritance
Polymorphism
Advantages of Object Oriented Programming
Simplicity: The objects in case of OOP are close to the real world objects, so the complexity of
the program is reduced making the program structure very clear and simple. For example, by
looking at the class Student, we can simply identify with the properties and behavior of a
student. This makes the class student very simple and easy to understand.
Modifiability: It is easy to make minor changes in the data representation or the procedures in
an OOP program. Changes inside a class do not affect any other part of a program, since the
only public interface that the external world has to a class is through the use of methods
Extensibility and Maintainability: It is quite easy to add new features and extend the new
program in case of object oriented programming. It can be simply done by introducing a few
objects and modifying some existing ones. The original base class need not be modified at all.
Even objects can be maintained separately, there by locating and fixing problems easier. For
example if a new attribute of the class Student needs to be added, a new derived class of the
class Student may be created and no other class in the class hierarchy need to be modified.
1
Re-usability: Objects can be reused in different programs. The class definitions can be reused
in various applications. Inheritance makes it possible to define subclasses of data objects that
share some or all of the main class characteristics. It forces a more thorough data analysis,
reduces development time and ensures more accurate coding.
Security: Since a class defines only the data it needs to be concerned with, when an instance of
that class (an object) is run, the code will not be able to accidentally access other program data.
This characteristic of data hiding provides greater system security and avoids unintended data
corruption.
Class Definition
The class definition in Python begins with the keyword class. The first statement after class
definition will be the docstring which gives a brief description about the class. The following
shows the syntax for defining a class.
SYNTAX
Class ClassName:
„Optional class documentation string'
class suite
A class creates a new local namespace where all its attributes are defined. Attributes may be
data or functions. There are also special attributes in it that begins with double underscores (__).
For example, __doc__ gives us the docstring of that class. As soon as we define a class, a new
class object is created with the same name. This class object allows us to access the different
attributes as well as to instantiate new objects of that class.
Example Program
class Student:
"Common base class for al1l students"
studentcount = 0
def __init__ (self, rollno, name, course):
self.rollno=rollno
self. name = name
self.course= course
Student.studentcount + =1
def displayCount (self) :
Print ("Total students=", Student.studentcount )
def displayStudent (self) :
2
print ("Roll Number: ", self.rollno)
print ( "Name:”,self.name)
print ("Course: , self.course)
In the above program, we have created a class called Student. The variable studentcount is a
class variable whose value is shared among all instances of this class. This can be accessed
from inside the class or outside the class by giving Student.studentcount.
The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when we create a new instance of this class.
Class methods have only one specific difference from ordinary functions - they must have an
extra argument in the beginning of the parameter list. This particular argument is self which is
used for referring to the instance. But we need not give any value for this parameter when we
call the method. Python provides it automatically. self is not a reserved word in Python but just
a strong naming convention and it is always Convenient to use conventional names as it makes
the program more readable. So while defining our class methods, we must explicitly list self as
the first argument for each method, including __init__.
It also implies that if we have a method which takes no arguments, then we still have to define
the method to have a self-argument. Self is an instance identifier and is required so that the
statements within the methods can have automatic access to the current instance attributes.
CREATING OBJECTS
An object is created by calling the class name with the arguments defined in the __init__
method. We can access a method by using the dot operator along with the object. Similarly a
class name can be accessed by specifying the method name with the dot operator with the class.
Example Program
# First student object is created
stud1=Student (10, Jack", "MS" )
# Second student object is created.
stud2 =Student (20, "Jill ", "BE")
# Displays the details of First Student
stud1. displayStudent()
# Displays the details of Second Student.
stud2. displayStudent ()
print ("Total Number of Students: " Student.studentcount)
3
When the above code is executed, it produces the following result.
Roll Number: l0
Name: Jack
Course: MS
Roll Number : 20
Name: Jill
Course: BE
Total Number of Students: 2
Example Program
class Student:
“Common base class for all students”
def __init__(self, rollno, name, course) :
self. rollno=rollno
self.name = name
self. course = course
def displayStudent (self) :
print ( "Roll Number:", self. rollno)
print ( "Name :”, self.name)
print ("Course:”,self.course)
studl=Student (10, "Jack",”MS”)
stud1.displayStudent ()
at=getattr (stud1, 'name')
4
print ("getattr (studl, 'name'):", at)
print ("hasattr (studl, age) :", hasattr(stud1,‟age‟))
#New attribute inserted
print ("setattr (studl, age, 21) :", setattr (studl, 'age' , 21))
Stud1. displayStudent ()
print ("Age:", studl.age)
# Attribute age deleted
print(delattr (stud1. age) : ", delattr (studl, 'age'))
Stud1. displayStudent()
OUTPUT
Roll Number: 10
Name : Jack
Course : MS
getattr (studl, 'name‟): Jack
hasattr (studl, age) : False
setattr (studl, aqe, 21) : None
Roll Number: 10
Name : Jack
Course: MS
Age: 21
delattr (studl, age) : None
Roll Number: 10
Name : Jack
Course: MS
Python contains several built-in class attributes. These attributes are accessed using the dot
operator. The following gives the list of built-in class attributes.
1. __dict__: This attribute contains the dictionary containing the class's namespace.
2. __doc__: It describes the class or it contains the class documentation string. If
undefined, it contains None.
3. __name__: This attribute contains the class name.
5
4. __module__ :This contains the module name in which the class is defined. This attribute
is " __main__ " in interactive mode.
5. __bases__: This contains an empty tuple containing the base classes, in the order of their
occurrence in the base class list.
Output
Roll number : 10
Name: Jack
Course: MS
Student.__doc__: Common base class for all students
Student.__name__: Student
Student.__module__:__main__
Student.__bases__: ()
Student.__dict__:{„displayStudent‟:<function displayStudent at 0x7efdcc04 7758>,
6
„__module__‟: „__main__‟,‟__doc__‟:‟Common base class for all
students‟,‟__init__‟:<function __init__ at 0x7efdcc 0476e0>}
DESTRUCTORS IN PYTHON
Python automatically deletes an object that is no longer in use. This automatic destroying of
objects is known as garbage collection. Python periodically performs the garbage collection to
free the blocks off memory that are no longer in use. But a class can implement the special
method __del__() called a destructor, that is invoked when the instance is about to be destroyed.
This method might be used to clean up any non memory resources used by an instance. The
following program shows the destructors in Python.
Example Program
Class Student:
“Common base class for all students”
def __init__ (self, rollno, name , course):
self. rollno=rollno
self. name = name
self. course = course
def displayStudent (self) :
print ( "Roll Number:", self.rollno)
print ("Name : ", self.name)
print ("Course:”,self.course)
7
ENCAPSULATION
Encapsulation is the most basic concept of OOP. It is the combining of data and the functions
associated with that data in a single unit. In most of the languages including Python, this unit is
called a class. In simple terms we can say that encapsulation is implemented, through classes.
In fact the data members of a class can be accessed through its member functions only. It keeps
the data safe from any external interference and misuse. The only way to access the data is
through the functions of the class. In the example of the class Student, the class encapsulates the
data (rollno, name, course) and the associated functions into a single independent unit.
DATA HIDING
We can hide data in Python. For this we need to prefix double underscore for an attribute. Data
hiding can be defined as the mechanism of hiding the data of a class from the outside world or
to be precise, from other classes. This is done to protect the data from any accidental or
intentional access. In most of the object oriented programming languages, encapsulation is
implemented through classes. In a class, data may be made private or public. Private data or
function of a class cannot be accessed from outside the class while public data or functions can
be accessed from anywhere. So data hiding is achieved by making the members of class private.
Access to private members is restricted and is only available to the member functions of the
same class. However, the public part of the object is accessible outside the class. Once the
attributes are prefixed with the double underscore, it will not be visible outside the class. The
following program shows an example for data hiding in Python.
Example Program
Class HidingDemo:
"Program for Hiding Data"
__num=0
def numbercount (self) :
self. __num+=1
print ("Number Count=", self.__num)
number=HidingDemo ()
number. numbercount ()
print (number.__num)
OUTPUT
Number Count= 1
8
Traceback (most recent call last):
File " main.py", line 9, in <module>
Print number.__num
AttributeError: HidingDemo instance has no attribute „__num‟
The output shows that numbercount is displayed once,. When it is attempted to call the variable
number. __num from outside the function, it resulted in an error.
INHERITANCE
The mechanism of deriving a new class from an old class is known as inheritance. The old class
is known as base class or super class or parent class. The new one is called the subclass or
derived class or child class. Inheritance allows subclasses to inherit all the variables and
methods to their parent class. The advantage of inheritance is the reusability of code. Fig. 7.1
illustrates the single inheritance. The attributes and methods of parent class will be available in
child class after inheritance.
Parent
Child
Class Student:
"Common base class for all students"
def getData (self, rollno, name, course):
self. rollno=rollno
self. name = name
self. course = course
9
def displayStudent (self) :
print ( "Roll Number:", self.rollno)
print ("Name : ", self.name)
print ("Course:”,self.course)
#Inheritance
Class Test(Student):
def getMarks(self,marks):
self,marks=marks
def displayMarks(self):
print(“Total marks:”,self.marks)
r=int(input(“Enter Roll Number:”))
n= input ("Enter Name:")
c=input (" Enter Course Name: "))
m=int (input ("Enter Marks: "))
#creating the object
print ( "Result")
studl=Test () #instance
studl.getData (r, n, c)
studl.getMarks (m)
studl .displayStudent ()
studl.displayMarks ()
OUTPUT
Enter Roll Number: 20
Enter Name:Smith
Enter Course Name: MS
Enter Marks:200
Result
Roll Number: 20
Name: Smith
Course: MS
Total Marks: 200
10
Multilevel Inheritance
We have already discussed the mechanism of deriving a new class from one parent class. We
can further inherit the derived class to form a new child class. Inheritance which involves more
than one parent class but at different levels is called multilevel inheritance. Figure 7.2 illustrates
multilevel inheritance.
11
elif self.marks>240: self.grade=" Second Class"
else: self.grade=" Failed"
print(“Result:”,self.grade)
#Main Program
r= int (input (" Enter Roll Number: "))
n= input ("Enter Name:)
r= input ("Enter Course Name:")
m= int (input (Enter Marks; "))
#creating the object
print ("Result" )
studl.getData(r, n, c)
studl=Result () #instance of child
studl.getMarks (m)
studl. displayStudent ()
stud1. displayMarks ()
stud1. calculateGrade()
OUTPUT
Enter Roll Number: 12
Enter Name:Jones
Enter Course Name: MS
Bnter Marks:400
Result
Roll Number: 12
Name:Jones
Course: MS
Total Marks : 400
Result: First Class
Multiple Inheritance
It is possible to inherit from more than one parent class. Such type of inheritance is called
multiple inheritance. In this case all the attributes and methods of both the parent class will
be available in the child class after inheritance. Fig 7.3 illustrates multiple inheritance.
12
A B
class Sports:
def getSportsMarks (self, spmarks) :
self.spmarks=spmarks
def displaySportsMarks (self) :
print ("Sports Marks:", self.spmarks)
#Multiple Inheritance
class Result (Test, Sports) :
def calculateGrade (self):
m=self.marks+self. Spmarks
13
if m>480:self.grade=”Distinction”
elif m>360: self.grade=”First Class"
elif m>480: self ,qrade="Distinction"
elif m>240: self.grade= " Second Class"
else: self.grade=" Failed”
Print ("Result : ",self.grade)
#Main Program
r = int (input ( "Enter Roll Number: "))
n= input ( "Enter Name: ")
c= input ("Enter Course Name:")
m=int (input ("Enter Marks : ") )
s=int (input ( "Enter Sports marks:"))
#creating the object
print ("Result")
studl=Result() #instance of child
studl.getData (r,n,c)
studl.getMarks (m)
studl.getSportsMarks (s)
studl.displayStudent ()
studl.displayMarks ()
studl.displaySportsMarks ()
studl. calculateGrade ()
Output
Enter Roll Number: 10
Enter Name: Bob
Enter Course Name:MS
Enter Marks:190
Enter Sports marks: 200
Result
Roll Number: 10
Name: Bob
Course : MS
Total Marks: 190
14
Sports Marks: 200
Result : First class
15
print ("Id of the School:", self.sch_Id)
#main program
sc=School (10, "Jones", 100, "Jack" , "Math" , 80)
sc=.showStudent ()
sc.showTeacher ()
sc.showSchool ()
OUTPUT
Id number of the Student: 10
Name of the Student: Jones
Id of the Teacher: 100
Name of the Teacher: Jack
subject: Math
Id of the school: 80
METHOD OVERRIDING
Polymorphism is an important characteristic of Object Oriented Programming language. In
Object oriented Programming, polymorphism refers to a programming language's ability to
process objects differently depending on their data type or class. More specifically, it is the
ability to redefine methods for derived classes. We can override methods in the parent class.
Method overriding is required when we want to define our own functionality in the child class.
This is possible by defining a method in the child class that has the same name, same arguments
and same return type as a method in the parent class. When this method is called, the method
defined in the child class is invoked and executed instead of the one in the parent class. The
following shows an example program for method overriding.
Example Program
class Parent:
"Base class”
def __init__ (self, name) :
self. name= name
def displayName (self) :
print ( "Name : ",self.name)
def __del__(self):
class name = self.__class__.__name__
16
print (class_name, "destroyed" )
#Main Program
n=input ("Enter Name:")
a=input ("Enter Address:”)
obj=Child (n, a) #instance of child
obj.displayName () #Calling child' s method
del obj
Output
Enter Name :Jill
Enter Address : Klos
Name : Jill
Address: Klos
Child destroyed
In the above program, even though there are two methods with the same name displayName() is
available in child class, the method in the child class will be invoked. The method in the child
class has overridden the method in the parent class.
The following shows some generic functionality that can be overridden.
1__init__ ( self [, args...] )
Constructor (with any optional arguments)
17
Sample Call: obj = className (args)
2 __del__( self )
Destructor, deletes an object
Sample Call : del obj
3__ repr__ ( self )
Evaluatable string representation
Sample Call : repr (obj)
4 __str__ ( self )
Printable string representation
Sample Call : str (obj)
5 __cmp__ ( self, x )
Object comparison
Taming Python by
Sample Call : cmp (obj, x)
POLYMORPHISM
The word Polymorphism is formed from two words - poly and morph where poly means many
and morph means forms. So polymorphism is the ability to use an operator or function in
various forms. That is a single function or an operator behaves differently depending upon the
data provided to them. Polymorphism can be achieved in two ways: operator overloading and
function overloading. Unlike in C++ and Java, Python does not support function or method
overloading.
Operator Overloading
Operator overloading is one of the important features of object oriented programming. C++ and
Python supports operator overloading, while Java does not support operator overloading. The
mechanism of giving special meanings to an operator is known as operator overloading. For
example the operator + is used for adding two numbers. In Python this operator can also be
used for concatenating two strings. This + operator can be used for adding member variables of
two different class. The following example shows how „+‟ operator can be overloaded.
Example Program
class Abc:
def __init__(self,a,b):
self.a=a
self.b= b
18
def __str__(self):
return “”Abc (%d,%d)” %(self.a,self.b)
def __add__(self.a + other.a,self.b+other.b)
a1=Abc (2, 4)
Abc (5, -2)
print (al + a2)
Output
Abc(7,2)
SOLVED PROGRAMS
Define a class to represent a bank account. Include the following details like name of the
depositor, account number, type of account, balance amount in the account. Write methods to
assign initial values, to deposit an amount, withdraw an amount after checking the balance, to
display name, account number, account type and balance.
Program
class Customer:
"Common base class for all Customers"
def get Data (self, name, accno, acctype, balance) :
self. name=name
def displayCustomer (self) :
self.accno=accno
self. acctype=acctype
self.balance=balance
def displayCustomer(self):
print ("Customer Name: ", self.name)
print ("Account Number: ",self.accno)
print ("Account Type: ", self. acctype)
print ("Balance amount: ", self. balance)
def deposit(self,amount):
self.balance=self.balance+amount
def withdrawal (self, amount):
if self.balance-amount <0: print(“Insufficient Funds”)
else: self. balance=self.balance-amount
19
#Main Program
while ch!=5:
print ("1.New Customer")
print ( "2.Deposit" )
print ("3.Withdrawal" )
print (4 .Display")
print ("5. Exit")
ch=int (input ("Enter your choice: "))
if ch==l:
obj=Customer ()
n=input ( "Enter Name:")
no=int (input ("Enter Account Number: "))
t=input ("Enter Account Type (SB/C) :")
b=int (input ("Enter the Amount:"))
obj.getData (n, no, t,b)
if ch==2:
b=int (input ( "Enter the amount to be deposited:"))
obj.deposit (b)
if ch==3:
b=int (input ("Enter the amount to be withdrawn:"))
obj .withdrawal (b)
if ch==4:
obj.displayCustomer()
el se :print ("Program Terminated)
Output
1. New Customer
2.Deposit
3.Withdrawal
4.Display
5. Exit
Enter your choice: 1
Enter Name : Jith
Enter Account Number:123
Enter Account Type (SB/C) ):SB
20
Enter the Amount: 100
1.New Customer
2.Deposit
3.Withdrawal
4.Display
5.Exit
Enter your choice :2
Enter the amount to be deposited: 100
1.New Customer
2.Deposit
3.Withdrawal
4.Display
5.Exit
Enter your choice:3
Enter the amount to be withdrawn :250
Insufficient Funds
1.New Customer
2.Deposit
3.Withdrawal
4.Display
5.Exit
Enter your choice:4
Customer Name: Jith
Account Number: 123
Account Type: SE
Balance amount: 200
1,New Customer
2,Deposit
3.Withdrawal
4.Display
5. Exit
Enter your choice:5
Program Terminated
21
Write a program to implement the following. Create a base class called Person consisting of
name and code. Create 2 child classes a) Account with member pay and b) Admin with
experience and inherit the base class. Create a class Employee with name, code, experience and
pay by inheriting the above classes.
Program
class Person:
def get Person (self, name, code) :
self. name=name
self.code=code
def displayperson (self) :
print ("Name: ", self .name)
print ("Code: ", self.code)
class Account (Person) :
def getAccount (self, pay) :
self.pay=pay
def displayAccount (self):
print ("Payment :",self pay)
class Admin (Person):
def getAdmin (self, exp):
self.exp=exp
def displayAdmin (self) :
print ("Experience:",self.exp)
class Employee (Account, Admin) :
print ("New Final Class" )
n=input ("Enter Name: " )
C=input ("Enter Code: ")
p=int (input ("Enter payment: ") )
e=input ("Enter experience: ")
obj=Employee ()
obj .get Person (n, c)
obj.getAccount (p)
obj.getAdmin (e)
obj .displayPerson ()
obj. displayAccount ()
22
obj .displayAdmin ()
Output
New Final Class
Enter Name:jons
Enter Code:101
Enter payment :100000
Enter experience:3
Name:jons
Code:101
Payment :100000
Experience:3
Create a class called Staff with code and name. Create classes Teacher(subject, publication) ,
Typist(speed), Officer(grade). Using the typist class as base class, create 2 classes
Regular(salary) and Casual(daily wages). Implement a menu driven program for the same.
Program
class Staff:
def getStaff (self, code, name) :
self.code=code
self.name=name
def đisplayStaff (self) :
print (Code :", self.code)
print("Name:",self .name)
class Teacher (Staff) :
def getTeacher (self,subject,pub) :
self.subject=subject
self .pub=pub
def displayTeacher (self) :
print (Subject:", self . subject)
print ("Publication:", self .pub)
class Typist (Staff) :
def getTypist (self, speed) :
self.speed=speed
23
def displayTypist (self) :
print ("Speed of Typing:", self . speed)
class Officer (Staff):
def getOfficer (self, grade) :
self.grade=grade
def displayofficer (self) :
print ("Grade of Officer:", self.grade)
class Regular (Typist) :
def getRegular (self, salary) :
self.salary=salary
def displayRegular (self) :
print ("salary of Regular Typist:", self. salary)
Class Casual (Typist) :
def getCasual (self, wages) :
self.wages=wages
def displayCasual(self):
print(“Wages of casual typist:”,self.wages)
#Main Program
Ch=0
While ch!=5:
print ("1.Teacher" )
print ("2.Officer")
print ("3. Regular Typist ")
print ("4. Casual Typist")
print ("5. Exit")
ch=int (input ("Enter your choice: "))
if ch=l:
obj=Teacher ()
C=input ("Enter the code:" )
n=input ("Enter Name:")
S=input ( "Enter Subject : ")
p=input ("Enter Publication: ")
obj.getStaff (c,n)
obj.getTeacher (s, p)
24
obj. displayStaff ()
obj. displayTeacher ()
if ch==2 :
obj =Officer ()
C=input ("Enter the code:")
n=input ("Enter Name: ")
g=input ("Enter the Grade: ")
obj.getStaff (c, n)
obj.getOfficer (g)
obj. displayStaff ()
obj. displayofficer ()
if ch==3 :
obj=Regular ()
C=input ( "Enter the code:")
n=input ("Enter Name: ")
sp=input ("Enter the speed:")
sal=input ( "Enter the salary:" )
obj.getStaff (c, n)
obj.getTypist (sp)
obj .getRegular (sal)
obj.displaystaff ()
obj.displayTypist ()
obj.displayRegular ()
if ch==4:
obj=Casual ()
c=input ("Enter the code:”)
n=input(“ Enter Name :” )
sp=input ("Enter the speed:”)
w=input ("Enter the daily wages:")
obi.getStaff (c,n)
obj.getTypist (sp)
obj.getCasual (w)
obj.displayStaff ()
obj.displayTypist ()
25
obj.displayCasual ()
else :print ("Program Terminated" )
OUTPUT
1.Teacher
2.Officer
3.Regular Typist
4.Casual Typist
5. Exit
Enter your choice:1
Enter the code:100
Enter Name : Smith
Enter Subject:Science
Enter Publication: Wiley
Code: 100
Name: Smith
Subject: Science
Publication: Wiley
1.Teacher
2.0fficer
3.Regular Typist
4.Casual Typist
5.Exit
Enter your choice:2
Enter the code: 156
Enter Name: John
Enter the Grade: First
Code: 156
Name: John
Grade of officer: First
1.Teacher
2.Officer
3.Regular Typist
4. Casual Typist
26
5. Exit
Enter your choice : 3
Enter the code: 210
Enter Name :Jack
Enter the speed: 200
Enter the salary: 2000
Code: 210
Name: Jack
Speed of Typing: 200
Salary of Regular Typist: 2000
1.Teacher
2.Officer
3.Regular Typist
4.Casual Typist
5. Exit
Enter your Choice:4
Enter the code:406
Enter Name:Jill
Enter the speed: 180
Enter the daily wages:180
Code: 406
Name: Jill
Speed of Typing: 180
Wages of Casual Typist: 180
1.Teacher
2.Officer
3.Regular Typist
4.Casual Typist
5.Exit
Enter your choice:5
Program Terminated
27
EXCEPTION HANDLING
An exception is an abnormal condition that is caused by a runtime error in the program. It
disturbs the normal flow of the program. An example for an exception is division by 0.When
a Python script encounters a situation that it cannot deal with, it raises an Exception. An
exception is a Python object that represents an error.
If the exception object is not caught and handled properly, the interpreter will display an error
message. If we want the program to continue with the execution of the remaining code, then
we should try to catch the exception object thrown by the error condition and then display
appropriate messages for taking corrective actions. This task is known as exception
handling.
BUILT-IN EXCEPTIONS
Python has a collection of built-in exception classes. If the runtime error belongs to of the
pre-defined built-in exception, it will throw the object of the appropriate exception.
HANDLING EXCEPTIONS
Python uses a keyword try to prepare a block of code that is likely to cause an error and
throw an exception. An except block is defined which catches the exception thrown by the try
block and handles it. The try block can have one or more statements that could generate an
exception. If anyone statement generates an exception, then the remaining statements in the
block are skipped and execution jumps to the except block that is placed next to the try block.
The except block can have more than one statement and if the except parameter matches with
the type of the exception object, then the exception is caught and statements in the except
block will be executed. Every try block should be followed by atleast one except statement.
try... except
The following gives the syntax of try ... except statement
Syntax
try:
suite
except Exception1:
Exceptionl_suite #Executes when Exceptionl occurs.
except Exception2:
Exception2_suite #Executes when Exception2 Occurs
else:
else_suite #Executes if there is no Exception in the try block.
28
When an exception occurs inside a try block, it will go to the corresponding except block. If
no exception is raised inside a try block then after the try block, the statements in the else
block is executed. The else block can also be considered a place to put the code that does not
raise any exception.
Example Program
#Exception Handling
try:
a=int (input ("First Number: "))
b=int (input ("Second Number: "))
result=a/b
print ("Result=", result)
except ZeroDivisionError:
print ("Division by Zero")
else:
print ( "Successful Division")
Output
First Number: 10
Second Number:0
Division by Zero
In the above example, the second number is 0. Since division by zero is not possible, an
exception is thrown and the execution goes to the except block. All the rest of the statements,
is bypassed in the try block. Hence the output is displayed as Division by Zero.
Example Program 2
#Exception Handling
try:
a=int (input ("First Number: "))
b=int (input ("Second Number: "))
result=a/b
print ( "Result=", result)
except ZeroDivisionError:
print ( "Division by Zero")
else:
29
print ("Successful Division")
Output
First Number: 20
Second Number: 10
Result=2
Successful Division
In the above example, exception is not thrown and hence all the statements in the try block is
executed. After executing the try block, the control passes on to the else block. Hence the
print statement in the else block is executed.
except clause with no Exception
We can use except statement with no exceptions. This kind of try-except statement catches
all the Exceptions. Since it catches all the exceptions, it will not help the programmer to
exactly identify what is the cause for the error occurred. Hence it is not considered as a good
programming practice. The following shows the syntax for except clause with no exception.
Syntax
try:
Suite
except:
Exception_suite #Executes when whatever Exception occurs.
else:
else_suite #Executes 1f there is no Exception in the try block
Example Program
#Exception Handling
try:
a=int (input(“First Number; ") )
b=int (input (“Second Number; ") )
result=a/b
print (“Result=" , result)
except :
print (“Error Occured")
else:
print ("Successful Division")
30
Output
First Number : 2
Second Number : 0
Error Occurred
except clause with multiple Exceptions
This is used when we want to give multiple exceptions in one except statement. The
following shows the syntax of the except clause with multiple exceptions.
Syntax
try:
suite
except (Exceptionl [, Exception2 [, . . . ExceptionN] ]]):
Exception_suite #Executes when whatever Exception specified occurs.
else:
else _suite # Executes if there 1s no Exception in the try block.
Example Program
# Exception Handling
try:
a=int (input ("First Number: "))
b=int (input ("Second Number: "))
result=a/b
print ("Result=",result)
except (ZeroDivisionError , TypesError):
print ("Error Occured")
else:
print(“Successful Division")
Output
First Number: 10
Second Number: 0
Error Occurred
31
try...finally
A finally block can be used with a try block. The code placed in the finally block is executed
no matter exception is caused or caught. We cannot use except clause and finally clause
together with a try block. It is also not possible to use else clause and finally together with a
try block. The following gives the syntax for a try..finally block.
Syntax
try:
suite
finally:
finally_suite #Executed always after the try block.
Example Program 1
#Exception Handling
try:
a=int (input ("First Number: "))
b=int (input ("Second Number: "))
result=a/b
print ("Result=" , result)
finally:
print (“Executed Always")
Output
First Number :20
Second Number: 0
Executed Always
Traceback (most recent call last):
File "main.py" Line 5, in <module>
result=a/b
ZeroDivisionError: integer division or modulo by zero
In the above example, an error occurred in the try block. It is caught by the Python‟s error
handling mechanism. But the statement in the finally block is executed even though an error
has occurred.
32
Example Program 2
#Exception Handling
try:
a=int (input ("First Number: "))
b=int (input ("Second Number: "))
result=a/b
print (“Result=" , result)
finally:
print (“Executed Always")
Output
First Number: 10
Second Number:5
Result=2
Executed Always
In the above example there was no exception thrown. Hence after the try block, the finally
block is executed.
Example Program
def display (a) :
try:
return int (a)
33
except ValueError As argumentl:
print (“Argument does not contain numbers", argument1)
#Function Call
display ("a")
Output
Argument does not contain numbers invalid literal for int () with base 10:‟a‟
In the above example, the function display is called with string arguments. But the actual
function is defined with integer parameter. Hence an exception is thrown and it is caught by
the except clause.
RAISING AN EXCEPTION
We have discussed about raising built-in exceptions. It is also possible to define a new
exception and raise it if needed. This is done using the raise statement. The following shows
the syntax of raise statement. An exception can be a string, a class or an object. Most of the
exceptions that the Python raises are classes, with an argument that is an instance of class.
This is equivalent to throw clause in Java.
Syntax
raise [Exception [, argument [, traceback] ]
Here, exception is the type of exception (for example, IOError) and argument is a value for
the exception argument. This argument is optional. The exception argument is None if we
does not supply any argument. The argument, traceback, is also optional. If this is used, then
the traceback object is used for the exception. This is rarely used in programming.
In order to catch the exception defined using the raise Statement, we need to use the except
clause. The following code shows how an exception defined using the raise statement can be
used.
Example Program
# Raising an Exception
a=int (input ("Enter the parameter value: "))
try:
if a<=0 :
raise ValueError ("Not a Positive Integer")
except ValuError as err:
34
print (err)
else:print ("Positive Integer=", a)
Output
Enter the parameter value:-9
Not a Positive Integer
USER-DEFINED EXCEPTION
Python also allows us to create our own exceptions by deriving classes from the standard built-in
exceptions. In the try block, the user-defined exception is raised and caught in the except block.
This is useful when we need to provide more specific information when an exception is caught.
The following shows an example for user-defined exception.
Example Program
# define Python user-defined exceptions
class Error (Exception):
“” "Base class for other exceptions""”
pass
class ValueTooSmallError (Error):
“” "Raised when the input value is too small"""
pass
class Value TooLargeError (Error):
“”” Raised when the input value is too large”””
pass
#Main Program
number=10
while True:
try:
i_num=int (“Input ("Enter a number:”))
if i_num< number:
raise ValueTooSmallError
elif i_ num> number:
raise ValueTooLargeError
break
35
except ValueTooSmallError:
print (This value is too small, try again!")
exceptValueTooLargeError:
print ("This value is too large, try again! ")
print ("Congratulations ! You guessed it correctly. ")
Output
Enter a number: 13
This value is too large, try again!
Enter a number: 9
This value is too small, try again!
Enter a number: 10
Congratulations! You guessed it correctly.
Here, we have defined a base class called Error. The other two exceptions
(ValueTooSmallError and Value Too LargeError) that are actually raised by our program are
derived from this class. This is the standard way to define user-defined exceptions in Python
programming, but you are not limited to this way only.
ASSERTIONS IN PYTHON
An assertion is a checking in Python that can be turned on or off while testing a program. In
assertion, an expression is tested and if the result is False, an exception is raised. Assertions
are done using the assert statement. The application of assertion is to check for a valid input
or for a valid output. The following shows the syntax for assert statement.
Syntax
Assert Expression [,Arguments]
36
traceback.
Example Program
#Python Assertions
def sum (a,b) :
sum=a+b
assert (sum>0), "Too low value”
return (sum)
a=int (input ("First Number: "))
b=int (input ("Second Number:”))
print (sum (a, b))
Output
First Number: -8
Second Number:-2
Traceback (most recent call last):
File “main.py", line 8, in <module>
print sum (a,b)
File "main.py", line 4, in sum
assert (sum>0), "Too low value"
AssertionError: Too low value
REGULAR EXPRESSION
Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly
specialized programming language embedded inside Python and made available through the re
module. A regular expression helps to match or find other strings or sets of strings, using à
specialized syntax held in a pattern. They are widely used in UNIX world.
The re module raises the exception re.error if an error occurs while compiling or using a regular
expression. There are various characters, which have special meaning when they are used in
regular expression. While dealing with regular expressions, we use raw strings as r „expression.
37
syntax of match() function.
Syntax
re.match (pattern, string, flags= 0)
where pattern is the regular expression to be matched, string is searched to match the pattern at
the beginning of string, flags are modifiers specified using bitwise OR(|). The re.match() returns
a match object if the matching was success and returns None, if matching was a failure.
Two functions group(n) and groups() of match object are used to get matched expression. The
group(n) method returns entire match (or specific subgroup n) and groups() method returns all
matching subgroups in a tuple or empty if there weren't any matches.
Example Program
#Example program for match() function
import re
line=”Python programming is fun”
matchObj= re .match( r‟fun', line, re.M|re.I)
if matchObj:
print ( "match ->matchObj .group () :", matchObj.group ())
else:
print ("No match! !”)
OUTPUT
No match! !
The match() function always checks the beginning of the string. Even though the keyword "fun"
is there in the string it is not considered as a match since it does not appear at the beginning of
the string. Consider the below example.
Example Program
#Example program for match () function
import re
line ="Python programming is fun"
matchObj = re .match( r'python', line, re.M|re.I)
if matchobj :
print ( "match -> matchObj .group (): ", matchObj.group ())
else:
print ( "No match! !")
38
Output
match -> matchObj .group () : Python
In the above example the word "python" is found as a match since it appears at the beginning of
the string.
OUTPUT
No match!!
Search->searchObj.group():fun
39
In the above example, match() function returns nothing while search() function searches the
entire string to find a match.
SYNTAX
re.sub (pattern, repl, string, max=0)
This method replaces all occurrences of the regular expression pattern in string with repl,
substituting all occurrences. If value for max is provided, it will replace only the number of
occurrences specified in max. This method returns modified string. The following example
shows the application of sub method.
Example Program
import re
zipcode=”2004-959-559 # This is zipcode"
# Remove anything other than digits
num = re.sub(r‟\D‟,””,zipcode)
print ("Zip Code:”,num)
OUTPUT
Zip Code: 2004959559
40
Table 9.1 Modifiers and Descriptions in re module
41
Character Classes
42
Special Character Classes
Repetition Cases
findall() METHOD
The findall() method searches all patterns and returns a list. The following shows an example
for findall() method.
Example Program
import re
a = "hello 234789 world 63678 ok 1 ok 1115 alpha 88 beta 999g"
print (re.findall ("\d+", a) )
Output
['234789' , '63678', 1','1115', '88', 999]
In the above example, \d is any numeric characters ie 0,1,2,3,4,5,6,7,8,9, "+" represents one or
more previous character. Hence the regular expression searches for only numeric characters.
43
Compile() METHOD
The compile method compiles a regular expression pattern into a regular expression object
which can be used for matching using its match() and search() methods. The syntax of compile
is as follows.
re. compile (pattern, flags=0)
The expression's behaviour can be modified by specifying a flags value. Values can be any of
the following variables, combined using bitwise OR (the | operator). The sequence
prog=re.compile(pattern)
result=prog.match(string)
is equivalent to result = re.match (pattern, string). Similarly the sequence
prog =re.compile(pattern)
result = prog.search(string) is equivalent to result=re.search(pattern,string)
Using re.complie() and saving the resulting regular expression object for reuse is more efficient
when the expression will be used several times in a single progam.
Example Program
import re
file = open ("Abc. txt", "r")
text=file.readlines()
file.close()
# compiling the regular expression:
kevword = re. compile (r‟a‟)
#searching the file content line by line:
for line in text:
if keyword . search (line) :
print (line)
OUTPUT
#Only lines containing a is displayed
Ram is a boy
Geeta is a girl
44
PROGRAM
import re
listString = [ ]
string = "1,4,6-9,12-19"
def matches (l):
start, end = l.groups ()
return','join (str (i) for i in range (int (start), int (end) +1))
listString = (re.sub(„(\d+) - (\d+)', matches, string) ).split(',')
print (listString)
OUTPUT
[„1‟,‟4‟,,‟6‟,‟7‟,‟8‟,‟9‟,‟12‟,‟13‟,‟14‟,‟15‟,‟16‟,‟17‟,‟18‟,‟19‟].
2. Write a python program to check the validity of password input by users. Validation
(At least 1 letter between [a-z] and letter between [A-Z]. At least 1 number between [0-
9]. At least 1 character from [$#@]. Minimum length 6 characters. Maximum length 16
characters.
PROGRAM
import re
while True:
p=input(“Input your password:”)
if len(p)<6 or len(p)>16:
print(“Invalid password”)
elif not re.search(“[a-z]”,p):
print(“Invalid password”)
elif not re.search(“[0-9]”,p):
print(“Invalid password”)
elif not re.search(“[A-Z]”,p):
print(“Invalid password”)
elif not re.search(“[$#@]”,p):
print(“Invalid password”)
else:
print(“Valid password”)
break
45
OUTPUT
Input your password: ASD232@sdfl
Valid Password
3. Create a file Test.txt. Retrieve all lines that contain “the”.
PROGRAM
import re
file=open(“Test.txt”,”r”)
text=file.readlines()
#compiling the regular expression
keyword=re.compile(r,‟the „)
#searching the file content line by line
for line in text:
if keyword.search(line):
print(line)
OUTPUT
# only lines containing “the” is displayed
Green computing is the environmentally responsible use of computers and related resources.
Such practices include the implementation of energy-efficient central processing units.
One of the earliest initiatives toward green computing in the US was voluntary labeling
program known as Energy Star.
*****************************
46