SlideShare a Scribd company logo
1 of 46
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.
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)
• 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

Python Programming - Files & Exceptions
Python Programming - Files & ExceptionsPython Programming - Files & Exceptions
Python Programming - Files & ExceptionsOmid AmirGhiasvand
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python TutorialSimplilearn
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programmingsambitmandal
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objectsPraveen M Jigajinni
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor Shubham Vishwambhar
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
Python multithreaded programming
Python   multithreaded programmingPython   multithreaded programming
Python multithreaded programmingLearnbay Datascience
 
Python Control structures
Python Control structuresPython Control structures
Python Control structuresSiddique Ibrahim
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
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
 

What's hot (20)

Python Programming - Files & Exceptions
Python Programming - Files & ExceptionsPython Programming - Files & Exceptions
Python Programming - Files & Exceptions
 
Python recursion
Python recursionPython recursion
Python recursion
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programming
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Python multithreaded programming
Python   multithreaded programmingPython   multithreaded programming
Python multithreaded programming
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
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...
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 

Similar to Exception handling and function in python

Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial Akash Pandey
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptxsarthakgithub
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Python basics
Python basicsPython basics
Python basicsHoang Nguyen
 
Python basics
Python basicsPython basics
Python basicsTony Nguyen
 
Python basics
Python basicsPython basics
Python basicsYoung Alista
 
Python basics
Python basicsPython basics
Python basicsHarry Potter
 
Python basics
Python basicsPython basics
Python basicsFraboni Ec
 
Python basics
Python basicsPython basics
Python basicsJames Wong
 
Python basics
Python basicsPython basics
Python basicsTIB Academy
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsYashJain47002
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security ProfessionalsAditya Shankar
 

Similar to Exception handling and function in python (20)

Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Java introduction
Java introductionJava introduction
Java introduction
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 

Recently uploaded

High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 

Recently uploaded (20)

High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 

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.
  • 5.
  • 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)
  • 22.
  • 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__)