SlideShare a Scribd company logo
Python Session - 6
Anirudha Anil Gaikwad
gaikwad.anirudha@gmail.com
What you learn
 Python Errors and Built-in Exceptions
 Python Exception Handling - Try,Except and Finally
 Python OOP
 Python Operator Overloading
 Constructor
Python Errors
When writing a program encounter errors.
Error caused by not following the proper structure (syntax) of the language is called syntax
error or parsing error.
We can notice here that a colon is missing in the if statement.
Errors can also occur at runtime and these are called exceptions.
for example, when a file we try to open does not exist (FileNotFoundError), dividing a
number by zero (ZeroDivisionError), module we try to import is not found (ImportError)
etc.
Whenever these type of runtime error occur, Python creates an exception object. If
not handled properly, it prints a traceback to that error along with some details
about why that error occurred.
x=10
if x>5
print(x)
Built-in Exceptions
Built-in Exceptions
Built-in Exceptions
Python Exceptions
An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.
Python provides us with the way to handle the Exception so that the other part of the
code can be executed without any disruption. However, if we do not handle the exception,
the interpreter doesn't execute all the code that exists after the that.
The Exception Handling in Python is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
Python Exception Handling
In Python, exceptions can be handled using a try statement.
A critical operation which can raise exception is placed inside the try clause and the code
that handles exception is written in except clause.
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
Catching Specific Exceptions
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
Raising Exceptions
exceptions are raised when corresponding errors occur at run time, but we can forcefully
raise it using the keyword raise.
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
try...finally
try:
fileptr = open("file.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
We can use the finally block with the try block in which, we can pace the important code
which must be executed before the try statement throws an exception.
Custom Exceptions
sometimes you may need to create custom exceptions that serves your purpose.
In Python, users can define such exceptions by creating a new class. This exception class has
to be derived, either directly or indirectly, from Exception class. Most of the built-in
exceptions are also derived form this class.
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
Python OOP
Python is a multi-paradigm programming language. Meaning, it supports different
programming approach.
One of the popular approach to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
 Class
 Object
 Method
 Inheritance .
 Encapsulation
 Polymorphism
 Data Abstraction
Python OOP - Class and Object
A class is a blueprint for the object.
class ClassName:
<statement-1>
.
.
<statement-N>
The object is an entity that has state and behavior. It may be any real-world object like
tree,fruit etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute
objName = ClassConstructor()
Python OOP - Method and Inheritance
 Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
def MethodName(Argument1,Argument2):
 Inheritance provides code reusability to the program because we can use an existing
class to create a new class instead of creating it from scratch. In inheritance, the child
class acquires the properties and can access all the data members and functions defined
in the parent class. A child class can also provide its specific implementation to the
functions of the parent class.
class derived-class(base class1):
Python OOP - Inheritance Types
Python OOP - Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevent data
from direct modification which is called encapsulation
Python OOP - Polymorphism
Polymorphism is an ability (in OOP) to use common interface for multiple form (data types).
Python OOP - Data Abstraction
we can also perform data hiding by adding the double underscore (___) as a prefix to the
attribute which is to be hidden. After this, the attribute will not be visible outside of the
class through the object.
Operator Overloading in Python
Python operators work for built-in classes. But same operator behaves differently with
different types. For example, the + operator will, perform arithmetic addition on two
numbers, merge two lists and concatenate two strings.
Oerator Overloading allows same operator to have different meaning according to the
context is called operator overloading
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
There are two types of Constructors.
1) Parameterized Constructor
2) Non-parameterized Constructor
Constructor definition is executed when we create the object of this class.
In python, the method __init__ simulates the constructor of the class. This method is
called when the class is instantiated.
T H A N K S

More Related Content

PPTX
Python Session - 5
PPTX
Python Session - 3
PPTX
Python Session - 2
PPTX
Python Session - 4
PDF
Python revision tour i
PPTX
Introduction to python
PDF
Python-01| Fundamentals
DOCX
Python Interview Questions For Freshers
Python Session - 5
Python Session - 3
Python Session - 2
Python Session - 4
Python revision tour i
Introduction to python
Python-01| Fundamentals
Python Interview Questions For Freshers

What's hot (20)

PDF
Functions and modules in python
PPTX
Python 3 Programming Language
PPTX
11 Unit 1 Chapter 02 Python Fundamentals
PPTX
Python second ppt
DOCX
Python Interview Questions For Experienced
PPTX
Python training
PPT
Introduction to Python
PDF
Basic Concepts in Python
PDF
Python interview questions
PPTX
Python Tutorial Part 1
PPTX
Full Python in 20 slides
PDF
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
PPTX
The Awesome Python Class Part-3
DOCX
PYTHON NOTES
 
PDF
Get started python programming part 1
PPTX
Chapter 9 python fundamentals
PDF
First Steps in Python Programming
PDF
Lesson 03 python statement, indentation and comments
PDF
Python made easy
Functions and modules in python
Python 3 Programming Language
11 Unit 1 Chapter 02 Python Fundamentals
Python second ppt
Python Interview Questions For Experienced
Python training
Introduction to Python
Basic Concepts in Python
Python interview questions
Python Tutorial Part 1
Full Python in 20 slides
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
The Awesome Python Class Part-3
PYTHON NOTES
 
Get started python programming part 1
Chapter 9 python fundamentals
First Steps in Python Programming
Lesson 03 python statement, indentation and comments
Python made easy
Ad

Similar to Python Session - 6 (20)

PPTX
Python Unit II.pptx
PPTX
Exception handling with python class 12.pptx
PPTX
Python_UNIT-I.pptx
PPTX
Python Lecture 7
PPTX
Python for dummies
PDF
Python interview questions and answers
PPTX
Docketrun's Python Course for beginners.pptx
DOCX
Python interview questions and answers
PDF
Control structures functions and modules in python programming
PPTX
Exception Handling in python programming.pptx
PDF
Python Programming Course Presentations
PPTX
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
PDF
Interview-level-QA-on-Python-Programming.pdf
DOCX
These questions will be a bit advanced level 2
PPT
Unit iii
PPT
UNIT III.ppt
PPT
UNIT III (2).ppt
PPTX
Mastering python lesson2
PDF
Python Viva Interview Questions PDF By ScholarHat
PPTX
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
Python Unit II.pptx
Exception handling with python class 12.pptx
Python_UNIT-I.pptx
Python Lecture 7
Python for dummies
Python interview questions and answers
Docketrun's Python Course for beginners.pptx
Python interview questions and answers
Control structures functions and modules in python programming
Exception Handling in python programming.pptx
Python Programming Course Presentations
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
Interview-level-QA-on-Python-Programming.pdf
These questions will be a bit advanced level 2
Unit iii
UNIT III.ppt
UNIT III (2).ppt
Mastering python lesson2
Python Viva Interview Questions PDF By ScholarHat
Errorhandlingbyvipulkendroyavidyalayacrpfmudkhed.pptx
Ad

Recently uploaded (20)

PDF
System and Network Administraation Chapter 3
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
System and Network Administration Chapter 2
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Transform Your Business with a Software ERP System
PPTX
ai tools demonstartion for schools and inter college
PPTX
L1 - Introduction to python Backend.pptx
PDF
top salesforce developer skills in 2025.pdf
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
System and Network Administraation Chapter 3
PTS Company Brochure 2025 (1).pdf.......
Operating system designcfffgfgggggggvggggggggg
Softaken Excel to vCard Converter Software.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
System and Network Administration Chapter 2
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Transform Your Business with a Software ERP System
ai tools demonstartion for schools and inter college
L1 - Introduction to python Backend.pptx
top salesforce developer skills in 2025.pdf
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
VVF-Customer-Presentation2025-Ver1.9.pptx
Which alternative to Crystal Reports is best for small or large businesses.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Navsoft: AI-Powered Business Solutions & Custom Software Development
Odoo POS Development Services by CandidRoot Solutions
2025 Textile ERP Trends: SAP, Odoo & Oracle

Python Session - 6

  • 1. Python Session - 6 Anirudha Anil Gaikwad gaikwad.anirudha@gmail.com
  • 2. What you learn  Python Errors and Built-in Exceptions  Python Exception Handling - Try,Except and Finally  Python OOP  Python Operator Overloading  Constructor
  • 3. Python Errors When writing a program encounter errors. Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error. We can notice here that a colon is missing in the if statement. Errors can also occur at runtime and these are called exceptions. for example, when a file we try to open does not exist (FileNotFoundError), dividing a number by zero (ZeroDivisionError), module we try to import is not found (ImportError) etc. Whenever these type of runtime error occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred. x=10 if x>5 print(x)
  • 7. Python Exceptions An exception can be defined as an abnormal condition in a program resulting in the disruption in the flow of the program. Python provides us with the way to handle the Exception so that the other part of the code can be executed without any disruption. However, if we do not handle the exception, the interpreter doesn't execute all the code that exists after the that. The Exception Handling in Python is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.
  • 8. Python Exception Handling In Python, exceptions can be handled using a try statement. A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause. # import module sys to get the type of exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oops!",sys.exc_info()[0],"occured.") print("Next entry.") print() print("The reciprocal of",entry,"is",r)
  • 9. Catching Specific Exceptions try: # do something pass except ValueError: # handle ValueError exception pass except (TypeError, ZeroDivisionError): # handle multiple exceptions # TypeError and ZeroDivisionError pass except: # handle all other exceptions pass
  • 10. Raising Exceptions exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise. try: age = int(input("Enter the age?")) if age<18: raise ValueError; else: print("the age is valid") except ValueError: print("The age is not valid")
  • 11. try...finally try: fileptr = open("file.txt","r") try: fileptr.write("Hi I am good") finally: fileptr.close() print("file closed") except: print("Error") We can use the finally block with the try block in which, we can pace the important code which must be executed before the try statement throws an exception.
  • 12. Custom Exceptions sometimes you may need to create custom exceptions that serves your purpose. In Python, users can define such exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from Exception class. Most of the built-in exceptions are also derived form this class. class ErrorInCode(Exception): def __init__(self, data): self.data = data def __str__(self): return repr(self.data) try: raise ErrorInCode(2000) except ErrorInCode as ae: print("Received error:", ae.data)
  • 13. Python OOP Python is a multi-paradigm programming language. Meaning, it supports different programming approach. One of the popular approach to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP).  Class  Object  Method  Inheritance .  Encapsulation  Polymorphism  Data Abstraction
  • 14. Python OOP - Class and Object A class is a blueprint for the object. class ClassName: <statement-1> . . <statement-N> The object is an entity that has state and behavior. It may be any real-world object like tree,fruit etc. Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute objName = ClassConstructor()
  • 15. Python OOP - Method and Inheritance  Methods are functions defined inside the body of a class. They are used to define the behaviors of an object. def MethodName(Argument1,Argument2):  Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch. In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class. class derived-class(base class1):
  • 16. Python OOP - Inheritance Types
  • 17. Python OOP - Encapsulation Using OOP in Python, we can restrict access to methods and variables. This prevent data from direct modification which is called encapsulation Python OOP - Polymorphism Polymorphism is an ability (in OOP) to use common interface for multiple form (data types).
  • 18. Python OOP - Data Abstraction we can also perform data hiding by adding the double underscore (___) as a prefix to the attribute which is to be hidden. After this, the attribute will not be visible outside of the class through the object.
  • 19. Operator Overloading in Python Python operators work for built-in classes. But same operator behaves differently with different types. For example, the + operator will, perform arithmetic addition on two numbers, merge two lists and concatenate two strings. Oerator Overloading allows same operator to have different meaning according to the context is called operator overloading
  • 20. Python Constructor A constructor is a special type of method (function) which is used to initialize the instance members of the class. There are two types of Constructors. 1) Parameterized Constructor 2) Non-parameterized Constructor Constructor definition is executed when we create the object of this class. In python, the method __init__ simulates the constructor of the class. This method is called when the class is instantiated.
  • 21. T H A N K S