UNIT IV
Errors are nothing but mistakes in the code that are potentially harmful.
In Python, errors can be categorized into three main types: Syntax Errors, Logical Errors, and Exceptions.
Syntax Errors:
Syntax errors, also known as parsing errors, occur when the Python interpreter encounters an incorrect
statement or expression.
These errors are detected during the parsing of the code.
# Syntax Error Example
print("Hello, World" # Missing closing parenthesis
Logical Errors:
Logical errors occur when the code is syntactically correct but does not produce the expected
result.
These errors are harder to detect and require careful debugging.
# Logical Error Example
def add_numbers(a, b):
result = a * b # Multiplication instead of addition
return result
print(add_numbers(2, 3)) # Expecting 5, but it will print 6
Exceptions:
Exceptions are errors that occur during the execution of a program.
These errors disrupt the normal flow of the program.
Examples of exceptions include ZeroDivisionError, FileNotFoundError, TypeError, etc.
# Exception Example
num1 = 10
num2 = 0
try:
result = num1 / num2 # Division by zero
print(result)
except ZeroDivisionError as e:
print(f"Error: {e}")
Page 1
Built-in Exception in Python
Exception Class Event
IOError It gets raised when an input/output operation fails.
Zero Division Error It gets raised when division or modulo by zero takes place for all numeric types.
It gets raised when the result of an arithmetic operation is too large to be
Overflow Error
represented.
Import Error It gets raised when the imported module is not found.
Index Error It gets raised when the index of a sequence is out of range.
Indentation Error It gets raised when there is an incorrect indentation.
Syntax Error It gets raised by the parser when a syntax error is encountered.
Key Error It gets raised when the specified key is not found in the dictionary.
Name Error It gets raised when an identifier is not found in the local or global namespace.
It gets raised when a function or operation is applied to an object of an incorrect
Type Error
type.
It gets raised when a function gets an argument of the correct type but of an
Value Error
improper value.
Exception Handling with try, except, and finally:
The try block is used to enclose the code that might raise an exception.
The except block specifies the code to be executed if a particular exception occurs.
The finally block contains code that will be executed no matter what, whether an exception is raised or
not.
Syntax :
try :
#statements in try block
except :
#executed when error in try block
# Example with try, except, and finally
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError as ve:
print(f"ValueError: {ve}")
except ZeroDivisionError as zde:
print(f"ZeroDivisionError: {zde}")
Page 2
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("This block will be executed no matter what.")
Raise an Exception
In Python, you can raise an exception using the raise keyword. This is useful when you want to signal an
error or a specific condition in your code. You can either use one of the built-in exceptions or create
your own custom exception.
def divide_numbers(num1, num2):
if num2 == 0:
raise ZeroDivisionError("Cannot divide by zero")
else:
return num1 / num2
try:
result = divide_numbers(10, 0)
print(result)
except ZeroDivisionError as e:
print(f"Error: {e}")
Example of creating and raising a custom exception:
class NegativeNumberError(Exception):
def __init__(self, message="Number cannot be negative"):
[Link] = message
super().__init__([Link])
def process_positive_number(num):
if num < 0:
raise NegativeNumberError()
else:
print(f"Processing positive number: {num}")
try:
process_positive_number(-5)
except NegativeNumberError as e:
print(f"Error: {e}")
Page 3
File in Python
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
File handling
File handling is an integral part of programming. File handling in Python is simplified with
built-in methods, which include creating, opening, and closing files.
Types Of File in Python
There are two types of files in Python and each of them are explained below in detail with
examples for your easy understanding.
They are:
Binary file
Text file
Binary files in Python
Binary files are those which store entire data in the form of bytes, i.e a group of 8 bits each.
While retrieving data from the binary file, the programmer can retrieve it in the form of
bytes. Binary files can be used to store text, images, audio and video.
Most of the files that we see in our computer system are called binary files.
Example:
1. Document files: .pdf, .doc, .xls etc.
2. Image files: .png, .jpg, .gif, .bmp etc.
3. Video files: .mp4, .3gp, .mkv, .avi etc.
4. Audio files: .mp3, .wav, .mka, .aac etc.
5. Database files: .mdb, .accde, .frm, .sqlite etc.
6. Archive files: .zip, .rar, .iso, .7z etc.
7. Executable files: .exe, .dll, .class etc.
Text files in Python
Text files are those which store data in the form of characters or strings. Text files don’t have any
specific encoding and it can be opened in normal text editor itself.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Page 4
Configuration: ini, cfg, reg etc.
File operations:
1. Open a file
2. Read or write (perform operation)
3. Append
4. Close the file
Creating and Opening Text Files :
Python has a built-in function open() to open a file. This function returns a file handler
that provides methods for accessing the file
The open() method is the primary file handling function.
The basic syntax is:
file_handler = open('file_name', 'mode')
The open() function takes two elementary parameters for file handling:
1. The file_name includes the file extension and assumes the file is in the current
working directory. If the file location is elsewhere, provide the absolute or relative
path.
2. The mode is an optional parameter that defines the file opening method.
Access Modes of the Files
Mode Description
3.
1. “r” Opens the file in read only mode and this is the default mode.
2. “w” Opens the file for writing. If a file already exists, then it’ll get
overwritten. If the file does not exist, then it creates a new file.
3. “a” Opens the file for appending data at the end of the file automatically.
If the file does not exist it creates a new file.
4. “r+” Opens the file for both reading and writing.
5. “w+” Opens the file for reading and writing. If the file does not exist it
creates a new file. If a file already exists then it will get
overwritten.
6. “a+” Opens the file for reading and appending. If a file already exists, the
data is appended. If the file does not exist it creates a new file.
7. “x” Creates a new file. If the file already exists,
the operation fails. “rb” Opens the binary file in read-only
mode.
8. “wb” Opens the file for writing the data in binary format.
9. “rb+” Opens the file for both reading and writing in binary format.
Page 5
The with statement
The with statement is useful in the case of manipulating the files
The syntax to open a file using with the statement is given below.
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
It provides better exception handling and simplifies it by providing some cleanup tasks.
Reading or writing to a file is a common use of the with statement.
If the break, return, or exception occurs in the nested block of code then it automatically
closes the file, we don't need to write the close() function. It doesn't let the file to corrupt.
Example
with open("[Link]",'r') as f:
content = [Link]();
print(content)
Python Read From File
In order to read a file in python, we must open the file in read mode. The following
methods are :
1. read() → To read total data from the file.
2. read(n) → To read ‘n’ characters from the file.
3. readline() → To read only one line.
4. readlines() → To read all lines into a list.
Ex1 :File [Link] content
Hello everyone!!
This topic is very important
Please don't sleep
Once this topic done
Then happily you can sleep
Thanks for cooperating
f=open("[Link]", 'r')
data=[Link]()
print(data)
[Link]()
Ex2 : read(n) method
f=open("[Link]", 'r')
data=[Link](20)
print(data)
Page 6
[Link]()
Ex3: readline() method
f=open("[Link]", 'r')
line1=[Link]()
print(line1, end='')
line2=[Link]()
print(line2, end='')
line3=[Link]()
print(line3, end='')
[Link]()
Ex3 : readlines() method
f=open("[Link]", 'r')
lines=[Link]()
for line in lines:
print(line, end='')
[Link]()
Perform Write operation
The write() file method
Python provides a write() method to write a string or bytes sequence to a file. This function
returns a number that is the size of data stored in a single Write call.
The write() method takes a string as an argument and writes it to the text file.
It returns the number of characters being written on single execution of the write() method.
Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.
To write some text to a file, we need to open the file using the open method with one of
the following access modes.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new
file if no file exists.
We have two methods for writing data into a file as shown below.
write(string)
writelines(list)
Page 7
write (string)
Example:
# Python code to create a file
file = open('[Link]','w')
[Link]("This is the write command")
[Link]("It allows us to write in a particular file")
[Link]()
writelines() method
This method is used to write multiple strings to a file. We need to pass an iterable object like lists,
tuple, etc. containing strings to the writelines() method.
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“[Link]”, “w”)
my_file.writelines(fruits)
Python Append to File
To append data into a file we must open the file in ‘a+’ mode so that we will have access to both the
append as well as write modes.
Ex1 :
my_file = open(“[Link]”, “a+”)
my_file.write (“Strawberry”)
Ex2:
fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]
my_file = open(“[Link]”, “a+”)
my_file.writelines(fruits)
print(my_file)
Page 8
Classes and Objects:
Class:
In Python, a class is a blueprint for creating objects that share common attributes and
behaviors.
It defines the structure and behavior of an object.
Classes are fundamental concept in object-oriented programming (OOP) and provide a way
to organize and encapsulate related data and functionality.
Object :
An object is a bundleof related state (variables) and behavior (methods).
Objects contain variables, which rep- resents the state of information about the thing you are
trying to model, and the methods represent the behavior or functionality that you want it to
have.
Creating Classes in Python
Classes are defined by using the class keyword, followed by the ClassName and a colon.
Let's see an example,
class Bike:
name = ""
gear = 0
Here,
Bike - the name of the class
name/gear - variables inside the class with default values "" and 0 respectively.
Note: The variables inside a class are called attributes
Creating Objects in Python
Page 9
Object refers to a particular instance of a class where the object contains variables and
methods defined in the class.
Class objects support two kinds of operations: attribute references and instantiation.
The term attribute refers to any name (variables or methods) following a dot.
The act of creating an object from a class is called instantiation.
The syntax for Class instantiation is,
object_name = ClassName(argument_1, argument_2, ….., argument_n)
The syntax to access data attribute is,
object_name.data_attribute_name
The syntax to assign value to data attribute is,
object_name.date_attribute_name = value
where value can be of integer, float, string types, or another object itself.
The syntax to call method attribute is,
object_name.method_attribute_name( )
Example 1: Python Class and Objects
# define a class
class Bike:
name = ""
gear = 0
# create object of class
bike1 = Bike()
# access attributes and assign new values
[Link] = 11
[Link] = "Mountain Bike"
print(f"Name: {[Link]}, Gears: {[Link]} ")
Output
Name: Mountain Bike, Gears: 11
Create Multiple Objects of Python Class
We can also create multiple objects from a single class.
For example,
# define a class
class Employee:
Page 10
employee_id = 0 # define an attribute
# create two objects of the Employee class
emp1 = Employee()
emp2 = Employee()
# access attributes using employee1
[Link] = 1001
print(f"Employee ID: {[Link]}")
# access attributes using employee2
[Link] = 1002
print(f"Employee ID: {[Link]}")
Output
Employee ID: 1001
Employee ID: 1002
In the above example, we have created two objects emp1 and emp2 of the Employee class.
Python Methods
A Python function defined inside a class is called a method.
Let's see an example,
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", [Link] * [Link])
# create object of Room class
study_room = Room()
# assign values to all the attributes
study_room.length = 42.5
study_room.breadth = 30.8
# access method inside class
study_room.calculate_area()
Page 11
Output
Area of Room = 1309.0
The Constructor Method
Python uses a special method called a constructor method.
Python allows us to define only one constructor per class.
It is also known as the_ init_ _() method, it will be the first method definition of a class
Its syntax of _ init_ _() method is,
The __init__ is a special method that automatically runs when an instance of class is created.
The parameters represent the data attributes.
It is invoked as soon as an object of a class is instantiated
The parameters for init () method are initialized with the arguments that we had passed
during instantiation of the class object.
The __init__() method defines and initializes the instance variables.
Self Parameter :
The self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class.
Note : Self is the instance itself. You can use any word instead of “self”
Example1 :
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print(f"Hello, my name is {[Link]} and I'm {[Link]} years old.")
person1 = Person("Amit", 22)
person2 = Person("Neha", 23)
print([Link]) # Output: Amit
Page 12
print([Link]) # Output: 23
[Link]() # Output: Hello, my name is Amit and I'm 22 years old.
[Link]() # Output: Hello, my name is Neha and I'm 23 years old.
Example2 :
Write Python Program to Calculate the Arc Length of an Angle by Assigning Values to the Radius and
Angle Data Attributes of the class ArcLength
import math
class ArcLength:
def __ init__ (self):
[Link] = 0
[Link] = 0
def calculate_arc_length(self):
result = 2 * [Link] * [Link] * [Link] / 360
print(f"Length of an Arc is {result}")
al = ArcLength() # creating object
[Link] = 9
[Link] = 75
print(f"Angle is {[Link]}")
print(f"Radius is {[Link]}")
al.calculate_arc_length()
OUTPUT
Angle is 75
Radius is 9
Length of an Arc is 11.780972450961725
Using Objects as Arguments
An object can be passed to a calling function as an argument.
Program to Demonstrate Passing of an Object as an Argument to a Function Call
class Track:
def init (self, song, artist):
[Link] = song
[Link] = artist
def display_details(vocalist):
Page 13
print(f"Song is '{[Link]}'")
print(f"Artist is '{[Link]}'")
singer = Track("The First Time Ever I Saw Your Face", "Roberta Flack")
display_details(singer)
Objects as Return Values
In Python,“everything is an object” (that is, all values are objects).
Anything that can be used as a value (int, str, float, functions, modules, etc.) is implemented as an
object.
The id ( ) function is used to find the identity of the location of the object in memory.
Thesyntax for id() function is,
id(object)
This function returns the “identity” of an object.
This is an integer (or long integer), which is guaranteed to be unique and constant for this object
during its lifetime.
Two objects with non-overlapping lifetimes may have the same id() value.
Encapsulation- Definition
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP).
Encapsulation is the process of bundling the data (attributes) and the methods
(functions) that operate on the data within a single unit, called a class.
In Encapsulation, the variables are not accessed directly; it is accessed through the methods
present in the class.
Encapsulation → Information Hiding
Abstraction → Implementation Hiding
In Python, encapsulation is implemented using public and private access modifiers for attributes and
methods:
Public members: These members are accessible from outside the class. You can access them
using the dot (.) operator on an object.
Private members: These members are intended to be restricted within the class. In Python, a
Page 14
single underscore (_) prefix is used to indicate that an attribute or method is private, but this is
more of a convention.
Private instance variable :
In Python, you can create private instance variables by prefixing their names with a double
underscore (_ _). This practice is known as name mangling, and it makes it harder to access
these variables from outside the class.
class BankAccount:
def __init__(self, balance):
# Private attribute
self._balance = balance
# Public method to get the balance
def get_balance(self):
return self._balance
# Public method to deposit money
def deposit(self, amount):
if amount > 0:
self._balance += amount
print(f"Deposited ${amount}. New balance: ${self._balance}")
else:
print("Invalid deposit amount.")
# Public method to withdraw money
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
print(f"Withdrew ${amount}. New balance: ${self._balance}")
else:
print("Invalid withdrawal amount.")
# Creating an instance of BankAccount
account = BankAccount(1000)
# Accessing the balance through a public method
print("Current balance:", account.get_balance()) # Output: 1000
# Depositing money
[Link](500) # Output: Deposited $500. New balance: $1500
Page 15
# Withdrawing money
[Link](200) # Output: Withdrew $200. New balance: $1300
The Polymorphism - “Poly means many and morphism means forms”.
Page 16
Polymorphism in Python is the ability of one function or method to have different behaviors depending
on the object or class it is applied to. For example, the len function can return the length of a string, a
list, a tuple, or a dictionary.
A real-world example of polymorphism is suppose when if you are in classroom that time you behave
like a student, when you are in market at that time you behave like a customer, when you are at your
home at that time you behave like a son or daughter, such that same person is presented as having
different behaviors.
Program to Demonstrate Polymorphism in Python
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class
for x in (car1, boat1, plane1):
[Link]()
Page 17
Inheritance
Inheritance is the one of the most and essential concept of the Object
Oriented Programming. It is the process by which one class acquires the
properties from one or more classes.
Here the properties are the Data Members and member
functions. The new classes are created from the existing classes.
The newly created class is called "Derived" class.
The existing class is called "Base" class.
The Derived class also called with other names such as sub class,
child class and descendent.
The existing class is also called with other names such as super
class, parent class and ancestor.
The concept of inheritance therefore, frequently used to implement is-a
relationship.
REUSABILITY
The main reason to go to the concept of the Inheritance is reusing the existing
properties, whichis called reusability.
Note: The new class will have its own properties and properties acquiredfrom
the base class.
Inheriting classes in Python
The Syntax to inherit the properties from one class to another will be as
follow:
class derived_class(base class):
<class-suite> #body of the Derived_class
Page 18
TYPES OF INHERITANCES
Python has various types of Inheritances. The Process of Inheritance can be either Simple or
complex. This depends on the following points:
The Number of base classes used in the inheritance.
Nested derivation
Based on the above points the inheritances are classified in to the different types.
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multi-path Inheritance
Single Inheritance
When only one class is derived from a single base class, such derivation is called single
inheritance. It is the simplest form of Inheritance. The New class is termed as "Derived"
class and the existing class is called "Base" class. The newly created class contains the
entire characteristics from its base class.
#syntax_of_single_inheritance
class class1: #parent_class
pass
class class2(class1): #child_class
pass
obj_name = class2()
Example :
class A:
def add(self,x,y):
self.x=x
self.y=y
print("The addition is:",self.x+self.y)
class B(A): #Single Inheritance
def sub(self,x,y):
self.x=x
self.y=y
Page 19
print("The subtraction is:",self.x-self.y)
#read data into a and b
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
#create object from derived object
ob=B()
[Link](a,b)
[Link](a,b)
Multi-Level inheritance
The process of deriving a new class from a derived class is known as "Multilevel
Inheritance". The intermediate derived class is also known as middle base class. C is
derived from B. The class B is derived from A. Here B is called Intermediate base class.
The series of classes A, B and C is called "Inheritance Pathway".
The syntax of multi-level inheritance is given below.
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Object= class3()
Example:
class A:
def add(self,x,y):
self.x=x
self.y=y
print("The addition is:",self.x+self.y)
class B(A): #Single Inheritance
def sub(self,x,y):
self.x=x
Page 20
self.y=y
print("The subtraction is:",self.x-self.y)
class C(B):
def mul(self,x,y):
self.x=x
self.y=y
print("The product is:",self.x*self.y)
#read data into a and b
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
#create object from derived objectob=C()
[Link](a,b)
[Link](a,b)
[Link](a,b)
Multiple Inheritances
When two or more base classes are used in the derivation of new class, it is called "Multiple
Inheritance". The derived class C has all the properties of both class A and class B.
Example program on Multiple –Inheritance:
class A:
def add(self,x,y):
self.x=x
self.y=y
print("The addition is:",self.x+self.y)
class B:
def sub(self,x,y):
self.x=x
self.y=y
print("The is:",self.x-self.y)
#Multiple Inheritance
Page 21
class C(A,B):
def mul(self,x,y):
self.x=x
self.y=y
print("The is:",self.x*self.y)
#read data into a and b
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
#create object from derived object
ob=C( )
[Link](a,b)
[Link](a,b)
[Link](a,b)
Hierarchical inheritance: When we derive or inherit more than one child class from
one(same) parent class. Then this type of inheritance is called hierarchical inheritance.
#syntax_of_hierarchical_inheritance
class A: #parent_class
pass
class B(A): #child_class
pass
class C(A): #child_class
pass
class D(A): #child_class
pass
obj_1 = B() #Object_creation
obj_2 = C()
obj_3 = D()
Page 22
Example :
class Brands: #parent_class
brand_name_1 = "Amazon"
brand_name_2 = "Ebay"
brand_name_3 = "OLX"
class Products(Brands): #child_class
prod_1 = "Online Ecommerce Store"
prod_2 = "Online Store"
prod_3 = "Online Buy Sell Store"
class Popularity(Brands): #grand_child_class
prod_1_popularity = 100
prod_2_popularity = 70
prod_3_popularity = 60
class Value(Brands):
prod_1_value = "Excellent Value"
prod_2_value = "Better Value"
prod_3_value = "Good Value"
obj_1 = Products() #Object_creation
obj_2 = Popularity()
obj_3 = Value()
print(obj_1.brand_name_1+" is an "+obj_1.prod_1)
print(obj_1.brand_name_1+" is an "+obj_1.prod_1)
print(obj_1.brand_name_1+" is an "+obj_1.prod_1)
Hybrid Inheritance:
Hybrid inheritance satisfies more than one form of inheritance. Hybrid Inheritance is the
combinations of simple, multiple, multilevel and hierarchical inheritance.
Page 23
#Example_Hybrid_inheritance
class PC:
def fun1(self):
print(“This is PC class”)
class Laptop(PC):
def fun2(self):
print(“This is Laptop class inheriting PC class”)
class Mouse(Laptop):
def fun3(self):
print(“This is Mouse class inheriting Laptop class”)
class Student(Mouse, Laptop):
def fun4(self):
print(“This is Student class inheriting PC and Laptop”)
# Driver’s code
obj = Student()
obj1 = Mouse()
obj.fun4()
obj.fun3()
Super( ) Function: Super Function in python programming is the built in function used to access
the parent class member form the child class having same member name or method name.
#Super function example
class A:
def __init__(self):
print("Parent class Constructor")
class B(A):
def __init__(self):
print("Child class Constructor")
obj = B()
#Output
# Child class Constructor
Page 24
Note: We use super() function , if we want to access the parent class member from child class explicitly.
class A:
x = 100
def __init__(self):
print("Parent class Constructor")
def fun1(self):
print("Python supports all types of Inheritance")
class B(A):
x= 250
def fun1(self):
print("Child class method")
def __init__(self):
print("Child class Constructor")
super().__init__() #calling parent class Constructor
print(super().x) #calling parent class variable
super().fun1() #parent class method called
obj = B()
#Output
# Child class Constructor
# Parent class Constructor
# 100
# Python supports all types of Inheritance
Built-in inheritance methods in Python
Python has a few methods that help with inheritance.
The method isinstance() returns a boolean, telling you if an object is an instance of a class.
>>> obj = Boat()
>>> isinstance(obj, Car)
False
>>> isinstance(obj, Boat)
True
The method issubclass() tests if a class inherits from a class or not.
>>> class Vehicle:
... pass
...
>>> class Car(Vehicle):
... pass
...
>>> issubclass(Vehicle, Car)
Page 25
False
>>> issubclass(Car, Vehicle)
True
Page 26