SlideShare a Scribd company logo
Exception Handling in Python
A Python program terminates as soon
as it encounters an error. In Python, an
error can be a syntax error or an
exception
Dr.T.Maragatham
Kongu Engineering College,
Erode
Error – Syntax Error
• Syntax Error:
• Syntax errors occur when the parser detects an incorrect statement.
• Most syntax errors are typographical , incorrect indentation, or incorrect
arguments.
• Example:
• i=1
• while i<5
• print(i)
• i=i+1
• Shows:
• File "<string>", line 2
• while i<5 # : missing
• ^
• SyntaxError: invalid syntax
Error - Exception
• Exception: Even if a statement or expression is
syntactically in-correct, it may cause an error when an
attempt is made to execute it. Errors detected during
execution are called exceptions .
• Example:
• x=(10/0) or x=(10%0)
• print(x)
• Shows:
• Traceback (most recent call last):
• File "<string>", line 1, in <module>
• ZeroDivisionError: division by zero
• Exceptions come in different types, and the type
is printed as part of the message:
• the types in the example are ZeroDivisionError,
NameError and TypeError.
• The string printed as the exception type is the
name of the built-in name for the exception that
occurred.
Exception handling and function in python
The try block will generate an
exception, because x is not defined:
• try:
• print(x)
• except:
• print("An exception occurred")
• Since the try block raises an error, the except
block will be executed.
• Without the try block, the program will crash and
raise an error:
Many Exceptions
• You can define as many exception blocks as you want.
• Example
• Print one message if the try block raises a NameError and another
for other errors:
• #The try block will generate a NameError, because x is not defined:
• try:
• print(x)
• except NameError:
• print("Variable x is not defined")
• except:
• print("Something else went wrong")
Else
• You can use the else keyword to define a block of code to
be executed if no errors were raised:
• Example:
• #The try block does not raise any errors, so the else block is
executed:
• try:
• print("Hello")
• except:
• print("Something went wrong")
• else:
• print("Nothing went wrong")
Finally
• The finally block, if specified, will be executed regardless if
the try block raises an error or not.
• Example:
• #The finally block gets executed no matter if the try block
raises any errors or not:
• try:
• print(x)
• except:
• print("Something went wrong")
• finally:
• print("The 'try except' is finished")
• Here is an example of an incorrect use:
• d={}
• try:
• x = d[5]
• except LookupError:
• # WRONG ORDER
• print("Lookup error occurred")
• except KeyError:
• print("Invalid key used")
• #The try block will raise an error when trying to write
to a read-only file:
• try:
• f = open("demofile.txt")
• f.write("Lorum Ipsum")
• except:
• print("Something went wrong when writing to the
file")
• finally:
• f.close()
• Raise an exception
• As a Python developer you can choose to throw an
exception if a condition occurs.
• To throw (or raise) an exception, use the raise keyword.
• Example
• Raise an error and stop the program if x is lower than
0:
• x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
• raise SomeException: throws an exception (a
specific type of ball, like throwing only tennis
balls).
• except: catches all exceptions (regardless of
type).
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print
to the user.
• Example
• Raise a TypeError if x is not an integer:
• x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Python Custom Exceptions
• Python has numerous built-in exceptions that
force your program to output an error when
something in the program goes wrong.
• However, sometimes you may need to create
your own custom exceptions that serve your
purpose.
Creating Custom Exceptions
• Users can define custom exceptions by
creating a new class.
• This exception class has to be derived, either
directly or indirectly, from the built-in
Exception class.
• Most of the built-in exceptions are also
derived from this class.
Throw an Exception using “raise”
• name="Malar"
• age = 15
• print(name)
• print(age)
• if int(age)>17:
• print("You can vote")
• else:
• print("You can't vote")
• raise ValueError("Vote when you tern 18 year old")
Throw a Custom Exception
• class Age_Restriction(ValueError):
• pass
• name="Malar"
• age = 15
• print(name)
• print(age)
• if int(age)>17:
• print("You can vote")
• else:
• print("You can't vote")
• raise Age_Restriction("Vote when you tern 18 year old")
•
class exceptionName(baseException):
pass
• One use of custom exceptions is to break out
of deeply nested loops.
• For example, if we have a table object that
holds records (rows),
• which hold fields (columns),
• which have multiple values (items),
• we could search for a particular value
• found = False
• for row, record in enumerate(table):
• for column, field in enumerate(record):
• for index, item in enumerate(field):
• if item == target:
• found = True
• break
• if found:
• break
• if found:
• break
• if found:
• print("found at ({0}, {1}, {2})".format(row, column, index))
• else:
• print("not found")
• from prettytable import PrettyTable
list1=[“Anu",”18",“98"]
list2=[“Siva",“19",“96"]
table=PrettyTable([‘Name',’Age‘,’Mark’])
for x in range(0,3):
table.add_row(list1[x],list2[x])
print(table)
Exception handling and function in python
• class FoundException(Exception):
• pass
• found = False
• try:
• for row, record in enumerate(table):
• for column, field in enumerate(record):
• for index, item in enumerate(field):
• if item == target:
• raise FoundException()
• except FoundException:
• print("found at ({0}, {1}, {2})".format(row, column, index))
• else:
• print("not found")
Functions
• A function is a block of code which only runs
when it is called.
• You can pass data, known as parameters, into
a function.
• A function can return data as a result.
• Creating a Function
• In Python a function is defined using
the def keyword:
• Calling a Function
• To call a function, use the function name
followed by parenthesis:
• Arguments
• Information can be passed into functions as
arguments.
• def my_function(fname):
• print(fname + " Priya")
• my_function(“Anu")
• my_function(“Guna")
• my_function(“Sasi")
• def my_function(fname, lname):
• print(fname + " " + lname)
• my_function(“Arun") # Error
Arbitrary Arguments, *args
• If you do not know how many arguments that
will be passed into your function,
• add a * before the parameter name in the
function definition.
• def my_function(*kids):
• print("The youngest child is " + kids[2])
• my_function(“Aradhana", “Diya", “Roshan")
Keyword Arguments
• You can also send arguments with
the key = value syntax.
• This way the order of the arguments does not
matter.
• def my_function(child3, child2, child1):
• print("The youngest child is " + child3)
• my_function(child1 = “Aradhana", child2 =
“Diya", child3 = “Roshan")
Default Parameter Value
• The following example shows how to use a default parameter
value.
• If we call the function without argument, it uses the default
value:
• def my_function(country = "Norway"):
• print("I am from " + country)
• my_function("Sweden")
• my_function("India")
• my_function()
• my_function("Brazil")
Passing a List as an Argument
• You can send any data types of argument to a
function (string, number, list, dictionary etc.),
and it will be treated as the same data type
inside the function.
• def my_function(food):
• for x in food:
• print(x)
• fruits = ["apple", "banana", "cherry"]
• my_function(fruits)
Return Values
• To let a function return a value, use
the return statement:
• def my_function(x):
• return 5 * x
• print(my_function(3))
• print(my_function(5))
• print(my_function(9))
The pass Statement
• function definitions cannot be empty, but if
you for some reason have
a function definition with no content, put in
the pass statement to avoid getting an error.
• def myfunction():
pass
Recursion
• Python also accepts function recursion, which
means a defined function can call itself.
• def tri_recursion(k):
• if(k > 0):
• result = k + tri_recursion(k - 1)
• else:
• result = 0
• return result
• print("nnRecursion Example Results")
• print(tri_recursion(6))
Pass by reference vs value
• All parameters (arguments) in the Python
language are passed by reference.
• It means if you change what a parameter
refers to within a function, the change also
reflects back in the calling function.
• def changeme( mylist ):
• #"This changes a passed list into this function"
• mylist.append([1,2,3,4])
• print("Values inside the function: ", mylist)
• return
• # Now you can call changeme function
• mylist = [10,20,30]
• changeme( mylist )
• print("Values outside the function: ", mylist)
• # Function definition is here
• def changeme( mylist ):
• mylist = [1,2,3,4]; # This would assign new
reference in mylist
• print "Values inside the function: ", mylist
• # Now you can call changeme function
• mylist = [10,20,30];
• changeme( mylist );
• print "Values outside the function: ", mylist
Scope of Variables
• The scope of a variable determines the
portion of the program where you can access
a particular identifier.
• There are two basic scopes of variables in
Python −
• Global variables
• Local variables
Global vs. Local variables
• Variables that are defined inside a function
body have a local scope, and those defined
outside have a global scope.
• local variables can be accessed only inside the
function in which they are declared, whereas
global variables can be accessed throughout
the program body by all functions.
• total = 0; # This is global variable.
• # Function definition is here
• def sum( arg1, arg2 ):
• # Add both the parameters and return them."
• total = arg1 + arg2; # Here total is local variable.
• print("Inside the function local total : ", total)
• return total
• # Now you can call sum function
• sum( 10, 20 )
• print("Outside the function global total : ", total)
Lambda Forms:
• In Python, small anonymous (unnamed)
functions can be created with lambda
keyword.
• A lambda function in python has the following
syntax.
• lambda arguments: expression
• Lambda functions can have any number of
arguments but only one expression.
• The expression is evaluated and returned
• double = lambda x: x * 2
• print(double(5))
• def average(x, y):
• return (x + y)/2
• print(average(4, 3))
• may also be defined using lambda
• print((lambda x, y: (x + y)/2)(4, 3))
• double = lambda x,y:((x+y /2))
• print(double(4,3))
Python Documentation Strings
• a string literal is used for
documenting a module, function, class, or m
ethod.
• You can access string literals by __doc__
(notice the double underscores)
• (e.g. my_function.__doc__)
Docstring Rules :
• String literal literals must be enclosed with a
triple quote. Docstring should be informative
• The first line may briefly describe the object's
purpose. The line should begin with a capital
letter and ends with a dot.
• If a documentation string is a muti-line string
then the second line should be blank followed
by any detailed explanation starting from the
third line.
• def avg_number(x, y):
• """Calculate and Print Average of two
Numbers.
•
• Created on 29/12/2012. python-docstring-
example.py
• """
• print("Average of ",x," and ",y, " is ",(x+y)/2)
• print(avg_number.__doc__)

More Related Content

What's hot (20)

Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
Praveen M Jigajinni
 
Operators in java
Operators in javaOperators in java
Operators in java
AbhishekMondal42
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 

Similar to Exception handling and function in python (20)

Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
mustafatahertotanawa1
 
Introduction to Python Basics
Introduction to Python BasicsIntroduction to Python Basics
Introduction to Python Basics
Raghunath A
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
sarthakgithub
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
module 2.pptx
module 2.pptxmodule 2.pptx
module 2.pptx
mahendranaik18
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
Srinivas Narasegouda
 
Exception Handling using Python Libraries
Exception Handling using Python LibrariesException Handling using Python Libraries
Exception Handling using Python Libraries
mmvrm
 
Exception handling in python and how to handle it
Exception handling in python and how to handle itException handling in python and how to handle it
Exception handling in python and how to handle it
s6901412
 
Python Programming Course Presentations
Python Programming Course  PresentationsPython Programming Course  Presentations
Python Programming Course Presentations
DreamerInfotech
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI P
 
Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Introduction to Python Prog. - Lecture 3
Introduction to Python Prog. - Lecture 3Introduction to Python Prog. - Lecture 3
Introduction to Python Prog. - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
DrJasmineBeulahG
 
GE3151_PSPP_UNIT_5_Notes
GE3151_PSPP_UNIT_5_NotesGE3151_PSPP_UNIT_5_Notes
GE3151_PSPP_UNIT_5_Notes
Guru Nanak Technical Institutions
 
function ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptxfunction ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptx
trwdcn
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptxpython-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
avishekpradhan24
 
Python for beginners textbook slides ppt
Python for beginners textbook slides pptPython for beginners textbook slides ppt
Python for beginners textbook slides ppt
AnithaChristyAngelin
 
Introduction to Python Basics
Introduction to Python BasicsIntroduction to Python Basics
Introduction to Python Basics
Raghunath A
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
Srinivas Narasegouda
 
Exception Handling using Python Libraries
Exception Handling using Python LibrariesException Handling using Python Libraries
Exception Handling using Python Libraries
mmvrm
 
Exception handling in python and how to handle it
Exception handling in python and how to handle itException handling in python and how to handle it
Exception handling in python and how to handle it
s6901412
 
Python Programming Course Presentations
Python Programming Course  PresentationsPython Programming Course  Presentations
Python Programming Course Presentations
DreamerInfotech
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI P
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
DrJasmineBeulahG
 
function ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptxfunction ppt.pptx function ppt.pptx function ppt.pptx
function ppt.pptx function ppt.pptx function ppt.pptx
trwdcn
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
Raghu Kumar
 
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptxpython-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
avishekpradhan24
 
Python for beginners textbook slides ppt
Python for beginners textbook slides pptPython for beginners textbook slides ppt
Python for beginners textbook slides ppt
AnithaChristyAngelin
 
Ad

Recently uploaded (20)

Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Ad

Exception handling and function in python

  • 1. Exception Handling in Python A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception Dr.T.Maragatham Kongu Engineering College, Erode
  • 2. Error – Syntax Error • Syntax Error: • Syntax errors occur when the parser detects an incorrect statement. • Most syntax errors are typographical , incorrect indentation, or incorrect arguments. • Example: • i=1 • while i<5 • print(i) • i=i+1 • Shows: • File "<string>", line 2 • while i<5 # : missing • ^ • SyntaxError: invalid syntax
  • 3. Error - Exception • Exception: Even if a statement or expression is syntactically in-correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions . • Example: • x=(10/0) or x=(10%0) • print(x) • Shows: • Traceback (most recent call last): • File "<string>", line 1, in <module> • ZeroDivisionError: division by zero
  • 4. • Exceptions come in different types, and the type is printed as part of the message: • the types in the example are ZeroDivisionError, NameError and TypeError. • The string printed as the exception type is the name of the built-in name for the exception that occurred.
  • 6. The try block will generate an exception, because x is not defined: • try: • print(x) • except: • print("An exception occurred") • Since the try block raises an error, the except block will be executed. • Without the try block, the program will crash and raise an error:
  • 7. Many Exceptions • You can define as many exception blocks as you want. • Example • Print one message if the try block raises a NameError and another for other errors: • #The try block will generate a NameError, because x is not defined: • try: • print(x) • except NameError: • print("Variable x is not defined") • except: • print("Something else went wrong")
  • 8. Else • You can use the else keyword to define a block of code to be executed if no errors were raised: • Example: • #The try block does not raise any errors, so the else block is executed: • try: • print("Hello") • except: • print("Something went wrong") • else: • print("Nothing went wrong")
  • 9. Finally • The finally block, if specified, will be executed regardless if the try block raises an error or not. • Example: • #The finally block gets executed no matter if the try block raises any errors or not: • try: • print(x) • except: • print("Something went wrong") • finally: • print("The 'try except' is finished")
  • 10. • Here is an example of an incorrect use: • d={} • try: • x = d[5] • except LookupError: • # WRONG ORDER • print("Lookup error occurred") • except KeyError: • print("Invalid key used")
  • 11. • #The try block will raise an error when trying to write to a read-only file: • try: • f = open("demofile.txt") • f.write("Lorum Ipsum") • except: • print("Something went wrong when writing to the file") • finally: • f.close()
  • 12. • Raise an exception • As a Python developer you can choose to throw an exception if a condition occurs. • To throw (or raise) an exception, use the raise keyword. • Example • Raise an error and stop the program if x is lower than 0: • x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")
  • 13. • raise SomeException: throws an exception (a specific type of ball, like throwing only tennis balls). • except: catches all exceptions (regardless of type).
  • 14. The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user. • Example • Raise a TypeError if x is not an integer: • x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed")
  • 15. Python Custom Exceptions • Python has numerous built-in exceptions that force your program to output an error when something in the program goes wrong. • However, sometimes you may need to create your own custom exceptions that serve your purpose.
  • 16. Creating Custom Exceptions • Users can define custom exceptions by creating a new class. • This exception class has to be derived, either directly or indirectly, from the built-in Exception class. • Most of the built-in exceptions are also derived from this class.
  • 17. Throw an Exception using “raise” • name="Malar" • age = 15 • print(name) • print(age) • if int(age)>17: • print("You can vote") • else: • print("You can't vote") • raise ValueError("Vote when you tern 18 year old")
  • 18. Throw a Custom Exception • class Age_Restriction(ValueError): • pass • name="Malar" • age = 15 • print(name) • print(age) • if int(age)>17: • print("You can vote") • else: • print("You can't vote") • raise Age_Restriction("Vote when you tern 18 year old") •
  • 19. class exceptionName(baseException): pass • One use of custom exceptions is to break out of deeply nested loops. • For example, if we have a table object that holds records (rows), • which hold fields (columns), • which have multiple values (items), • we could search for a particular value
  • 20. • found = False • for row, record in enumerate(table): • for column, field in enumerate(record): • for index, item in enumerate(field): • if item == target: • found = True • break • if found: • break • if found: • break • if found: • print("found at ({0}, {1}, {2})".format(row, column, index)) • else: • print("not found")
  • 21. • from prettytable import PrettyTable list1=[“Anu",”18",“98"] list2=[“Siva",“19",“96"] table=PrettyTable([‘Name',’Age‘,’Mark’]) for x in range(0,3): table.add_row(list1[x],list2[x]) print(table)
  • 23. • class FoundException(Exception): • pass • found = False • try: • for row, record in enumerate(table): • for column, field in enumerate(record): • for index, item in enumerate(field): • if item == target: • raise FoundException() • except FoundException: • print("found at ({0}, {1}, {2})".format(row, column, index)) • else: • print("not found")
  • 24. Functions • A function is a block of code which only runs when it is called. • You can pass data, known as parameters, into a function. • A function can return data as a result.
  • 25. • Creating a Function • In Python a function is defined using the def keyword: • Calling a Function • To call a function, use the function name followed by parenthesis: • Arguments • Information can be passed into functions as arguments.
  • 26. • def my_function(fname): • print(fname + " Priya") • my_function(“Anu") • my_function(“Guna") • my_function(“Sasi")
  • 27. • def my_function(fname, lname): • print(fname + " " + lname) • my_function(“Arun") # Error
  • 28. Arbitrary Arguments, *args • If you do not know how many arguments that will be passed into your function, • add a * before the parameter name in the function definition. • def my_function(*kids): • print("The youngest child is " + kids[2]) • my_function(“Aradhana", “Diya", “Roshan")
  • 29. Keyword Arguments • You can also send arguments with the key = value syntax. • This way the order of the arguments does not matter. • def my_function(child3, child2, child1): • print("The youngest child is " + child3) • my_function(child1 = “Aradhana", child2 = “Diya", child3 = “Roshan")
  • 30. Default Parameter Value • The following example shows how to use a default parameter value. • If we call the function without argument, it uses the default value: • def my_function(country = "Norway"): • print("I am from " + country) • my_function("Sweden") • my_function("India") • my_function() • my_function("Brazil")
  • 31. Passing a List as an Argument • You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. • def my_function(food): • for x in food: • print(x) • fruits = ["apple", "banana", "cherry"] • my_function(fruits)
  • 32. Return Values • To let a function return a value, use the return statement: • def my_function(x): • return 5 * x • print(my_function(3)) • print(my_function(5)) • print(my_function(9))
  • 33. The pass Statement • function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error. • def myfunction(): pass
  • 34. Recursion • Python also accepts function recursion, which means a defined function can call itself. • def tri_recursion(k): • if(k > 0): • result = k + tri_recursion(k - 1) • else: • result = 0 • return result • print("nnRecursion Example Results") • print(tri_recursion(6))
  • 35. Pass by reference vs value • All parameters (arguments) in the Python language are passed by reference. • It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
  • 36. • def changeme( mylist ): • #"This changes a passed list into this function" • mylist.append([1,2,3,4]) • print("Values inside the function: ", mylist) • return • # Now you can call changeme function • mylist = [10,20,30] • changeme( mylist ) • print("Values outside the function: ", mylist)
  • 37. • # Function definition is here • def changeme( mylist ): • mylist = [1,2,3,4]; # This would assign new reference in mylist • print "Values inside the function: ", mylist • # Now you can call changeme function • mylist = [10,20,30]; • changeme( mylist ); • print "Values outside the function: ", mylist
  • 38. Scope of Variables • The scope of a variable determines the portion of the program where you can access a particular identifier. • There are two basic scopes of variables in Python − • Global variables • Local variables
  • 39. Global vs. Local variables • Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. • local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions.
  • 40. • total = 0; # This is global variable. • # Function definition is here • def sum( arg1, arg2 ): • # Add both the parameters and return them." • total = arg1 + arg2; # Here total is local variable. • print("Inside the function local total : ", total) • return total • # Now you can call sum function • sum( 10, 20 ) • print("Outside the function global total : ", total)
  • 41. Lambda Forms: • In Python, small anonymous (unnamed) functions can be created with lambda keyword. • A lambda function in python has the following syntax. • lambda arguments: expression • Lambda functions can have any number of arguments but only one expression. • The expression is evaluated and returned
  • 42. • double = lambda x: x * 2 • print(double(5))
  • 43. • def average(x, y): • return (x + y)/2 • print(average(4, 3)) • may also be defined using lambda • print((lambda x, y: (x + y)/2)(4, 3)) • double = lambda x,y:((x+y /2)) • print(double(4,3))
  • 44. Python Documentation Strings • a string literal is used for documenting a module, function, class, or m ethod. • You can access string literals by __doc__ (notice the double underscores) • (e.g. my_function.__doc__)
  • 45. Docstring Rules : • String literal literals must be enclosed with a triple quote. Docstring should be informative • The first line may briefly describe the object's purpose. The line should begin with a capital letter and ends with a dot. • If a documentation string is a muti-line string then the second line should be blank followed by any detailed explanation starting from the third line.
  • 46. • def avg_number(x, y): • """Calculate and Print Average of two Numbers. • • Created on 29/12/2012. python-docstring- example.py • """ • print("Average of ",x," and ",y, " is ",(x+y)/2) • print(avg_number.__doc__)