BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Study Material
Python Programming (BES00007)
__________________________________________________________________________________________
Exceptions Handling
Python provides two very important features to handle any unexpected error in your Python programs and to add
debugging capabilities in them-
What is Exception?
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.
Standard Exceptions
Here is a list of Standard Exceptions available in Python.
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 [Link]() 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.
ZeroDivisonError 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.
Raised when there is no input from either the raw_input() or input()
EOFError
function and the end of file is reached.
ImportError Raised when an import statement fails.
Raised when the user interrupts program execution, usually by pressing
KeyboardInterrupt
Ctrl+c.
Department of CSE-AI
Brainware University, Kolkata 1
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
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.
Raised when trying to access a local variable in a function or method but no
UnboundLocalError
value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
Raised when an input/ output operation fails, such as the print statement or
IOError
the open() function when trying to open a file that does not exist.
OSError Raised for operating system-related errors.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
Raised when the interpreter finds an internal problem, but when this error
SystemError
is encountered the Python interpreter does not exit.
Raised when Python interpreter is quit by using the [Link]() function. If not
SystemExit
handled in the code, causes the interpreter to exit.
TypeError Raised when an operation or function 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.
Syntax
try:
You do your operations here
......................
Department of CSE-AI
Brainware University, Kolkata 2
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
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.
Here are few important points about the above-mentioned syntax-
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.
Example
This example opens a file, writes content in the file and comes out gracefully because there is no problem at all.
try:
fh = open("testfile", "w")
[Link]("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")
[Link]()
This produces the following result-
Written content in the file successfully
Example
This example tries to open a file where you do not have the write permission, so it raises an exception-
Department of CSE-AI
Brainware University, Kolkata 3
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
try:
fh = open("testfile", "r")
[Link]("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
This produces the following result-
Error: can't find file or read data
except Clause with No Exceptions
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is
not considered a good programming practice though, because it catches all exceptions but does not make the
programmer identify the root cause of the problem that may occur.
except Clause with Multiple Exceptions
You can also use the same except statement to handle multiple exceptions as follows-
Department of CSE-AI
Brainware University, Kolkata 4
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try-finally Clause
You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute,
whether the try-block raised an exception or not. The syntax of the try-finally statement is this-
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note: You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along
with a finally clause.
Example
try:
fh = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
[Link]()
If you do not have permission to open the file in writing mode, then this will produce the following result-
Error: can't find file or read data
Same example can be written more cleanly as follows-
Department of CSE-AI
Brainware University, Kolkata 5
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
try:
fh = open("testfile", "w")
try:
[Link]("This is my test file for exception handling!!")
finally:
print ("Going to close the file")
[Link]()
except IOError:
print ("Error: can\'t find file or read data")
When an exception is thrown in the try block, the execution immediately passes to finally block. After all the
statements in the finally block are executed, the exception is raised again and is handled in the except statements
if present in next higher layer of the try-except statement.
Argument of an Exception
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.
This variable receives the value of the exception mostly containing the cause of the exception. The variable can
receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the
error number, and an error location.
Example
Department of CSE-AI
Brainware University, Kolkata 6
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
# Define a function here.
def temp_convert(var):
try:
returnint(var)
except ValueError as Argument:
print("The argument does not contain numbers\n",Argument)
This produces the following result-
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
Raising an Exception
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is
as follows-
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object
used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes,
with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as
follows-
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception return level
Department of CSE-AI
Brainware University, Kolkata 7
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Note: In order to catch an exception, an "except" clause must refer to the same exception thrown
either as a class object or a simple string. For example, to capture the above exception, we must write the except
clause as follows-
try:
Business Logic here... except Exception as e:
else:
Rest of the code here...
Exception handling here using [Link]...
The following example illustrates the use of raising an exception-
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
try:
l=functionName(-10)
print ("level=",l)
except Exception as e:
print ("error in level argument",[Link][0])
This will produce the following result-
error in level argument -10
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is
useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to
create an instance of the class Networkerror.
class
Networkerror(RuntimeError):
def init (self, arg):
[Link] = arg
Department of CSE-AI
Brainware University, Kolkata 8
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
So once you have defined the above class, you can raise the exception as follows-
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print [Link]
Department of CSE-AI
Brainware University, Kolkata 9
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Object Oriented Programming
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in
programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the
programming. The main concept of OOPs is to bind the data and the functions that work on that together as a
single unit so that no other part of the code can access this data.
Main Concepts of Object-Oriented Programming (OOPs)
Class
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction
Class
A class is a collection of objects. A class contains the blueprints or the prototype from which the objects are being
created. It is a logical entity that contains some attributes and methods.
To understand the need for creating a class let’s consider an example, let’s say you wanted to track the number of
dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog’s breed
while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you
know which element is supposed to be which? What if you wanted to add other properties to these dogs? This
lacks organization and it’s the exact need for classes.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator. Eg.:
[Link]
Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
Example: Creating an empty Class in Python
Department of CSE-AI
Brainware University, Kolkata 10
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
class Dog:
pass
In the above example, we have created a class named dog using the class keyword.
Objects
The object is an entity that has a state and behavior associated with it. It may be any real-world object like a
mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are
all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the
string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You’ve been using
objects all along and may not even realize it.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
To understand the state, behavior, and identity let us take the example of the class dog (explained above).
The identity can be considered as the name of the dog.
State or Attributes can be considered as the breed, age, or color of the dog.
The behavior can be considered as to whether the dog is eating or sleeping.
Example: Creating an object
obj = Dog()
This will create an object named obj of the class Dog defined above. Before diving deep into objects and class let
us understand some basic keywords that will we used while working with objects and classes.
self
1. Class methods must have an extra first parameter in the method definition. We do not give a value for this
parameter when we call the method, Python provides it
2. If we have a method that takes no arguments, then we still have to have one argument.
3. This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as [Link](arg1, arg2), this is automatically converted by Python
into [Link](myobject, arg1, arg2) – this is all the special self is about.
Department of CSE-AI
Brainware University, Kolkata 11
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
__init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is
instantiated. The method is useful to do any initialization you want to do with your object.
Now let us define a class and create some objects using the self and __init__ method.
Example 1: Creating a class and object with class and instance attributes
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
[Link] = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class attributes
print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))
# Accessing instance attributes
print("My name is {}".format([Link]))
print("My name is {}".format([Link]))
Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
Department of CSE-AI
Brainware University, Kolkata 12
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Example 2: Creating Class and objects with methods
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
[Link] = name
def speak(self):
print("My name is {}".format([Link]))
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class methods
[Link]()
[Link]()
Output
My name is Rodger
My name is Tommy
Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class. The class that
derives properties is called the derived class or child class and the class from which the properties are being
derived is called the base class or parent class. The benefits of inheritance are:
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows
us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses
of B would automatically inherit from class A.
Types of Inheritance
Single Inheritance:
Single-level inheritance enables a derived class to inherit characteristics from a single-parent class.
Department of CSE-AI
Brainware University, Kolkata 13
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Multilevel Inheritance:
Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn
inherits properties from his parent class.
Hierarchical Inheritance:
Hierarchical level inheritance enables more than one derived class to inherit properties from a parent class.
Multiple Inheritance:
Multiple level inheritance enables one derived class to inherit properties from more than one base class.
Example: Inheritance in Python
# parent class
class Person(object):
# __init__ is known as the constructor
def __init__(self, name, idnumber):
[Link] = name
[Link] = idnumber
def display(self):
print([Link])
print([Link])
def details(self):
print("My name is {}".format([Link]))
print("IdNumber: {}".format([Link]))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
[Link] = salary
[Link] = post
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber)
def details(self):
print("My name is {}".format([Link]))
print("IdNumber: {}".format([Link]))
print("Post: {}".format([Link]))
# creation
Department of an object variable or an instance
of CSE-AI
Brainware University,
a = Employee('Rahul',Kolkata 886012, 200000, "Intern") 14
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Output
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern
Polymorphism
Polymorphism simply means having many forms. For example, we need to determine if the given species of birds
fly or not, using polymorphism we can do this using a single function.
Example: Polymorphism in Python
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
Department of CSE-AI
obj_spr.flight()
Brainware University, Kolkata 15
obj_ost.intro()
obj_ost.flight()
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Output
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of
wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables
and methods directly and can prevent the accidental modification of data. To prevent accidental change, an
object’s variable can only be changed by an object’s method. Those types of variables are known as private
variables.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
Example: Encapsulation in Python
Department of CSE-AI
Brainware University, Kolkata 16
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
# Creating a Base class
class Base:
def __init__(self):
self.a = "Python"
self.__c = "Python"
# Creating a derived class
class Derived(Base):
def __init__(self):
# Calling constructor of Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
obj1 = Base()
print(obj1.a)
Output
Python
In the above example, we have created the c variable as the private attribute. We cannot even access this
attribute directly and can’t even change its value.
Data Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial
or non-essential units are not displayed to the user. Ex: A car is viewed as a car rather than its individual
components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object,
ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the object.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will
increase the car speed or applying brakes will stop the car, but he does not know how on pressing the accelerator,
the speed is actually increasing. He does not know about the inner mechanism of the car or the implementation
of the accelerators, brakes etc. in the car. This is what abstraction is.
Department of CSE-AI
Brainware University, Kolkata 17
BTech CSE-AIML Semester-3
Python Programming (BES00007)
2025-26 (Odd Semester)
Department of CSE-AI
Brainware University, Kolkata 18