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__)
Ad

More Related Content

What's hot (20)

Threads in python
Threads in pythonThreads in python
Threads in python
baabtra.com - No. 1 supplier of quality freshers
 
Generators In Python
Generators In PythonGenerators In Python
Generators In Python
Simplilearn
 
Python file handling
Python file handlingPython file handling
Python file handling
Prof. Dr. K. Adisesha
 
stack & queue
stack & queuestack & queue
stack & queue
manju rani
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
BMS Institute of Technology and Management
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
Emertxe Information Technologies Pvt Ltd
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaWhat is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Edureka!
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Python recursion
Python recursionPython recursion
Python recursion
Prof. Dr. K. Adisesha
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Python Generators
Python GeneratorsPython Generators
Python Generators
Akshar Raaj
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
Ramakrishna Reddy Bijjam
 
Generators In Python
Generators In PythonGenerators In Python
Generators In Python
Simplilearn
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | EdurekaWhat is Multithreading In Python | Python Multithreading Tutorial | Edureka
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Edureka!
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Python Generators
Python GeneratorsPython Generators
Python Generators
Akshar Raaj
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
Shyam Gupta
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 

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
PranavSB
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
YashAgarwal413109
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
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 introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Exception Handling in python programming.pptx
Exception Handling in python programming.pptxException Handling in python programming.pptx
Exception Handling in python programming.pptx
shririshsri
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
chandankumar943868
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
Akash Pandey
 
Python for beginner, learn python from scratch.pptx
Python for beginner,  learn python from scratch.pptxPython for beginner,  learn python from scratch.pptx
Python for beginner, learn python from scratch.pptx
olieee2023
 
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
sakchaisengsui
 
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
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
sarthakgithub
 
03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Pythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptxPythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
Python basics
Python basicsPython basics
Python basics
Hoang Nguyen
 
Python basics
Python basicsPython basics
Python basics
Harry Potter
 
Python basics
Python basicsPython basics
Python basics
Fraboni Ec
 
Python basics
Python basicsPython basics
Python basics
James Wong
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
PranavSB
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
PranavSB
 
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
 
Exception Handling in python programming.pptx
Exception Handling in python programming.pptxException Handling in python programming.pptx
Exception Handling in python programming.pptx
shririshsri
 
Python for beginner, learn python from scratch.pptx
Python for beginner,  learn python from scratch.pptxPython for beginner,  learn python from scratch.pptx
Python for beginner, learn python from scratch.pptx
olieee2023
 
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
sakchaisengsui
 
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
 
03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf03-Variables, Expressions and Statements (1).pdf
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Pythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptxPythonlearn-02-Expressions123AdvanceLevel.pptx
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
Ad

Recently uploaded (20)

Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
roshinijoga
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Redirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to RickrollsRedirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to Rickrolls
Kritika Garg
 
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning ModelsMode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Journal of Soft Computing in Civil Engineering
 
Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Journal of Soft Computing in Civil Engineering
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
Parameter-Efficient Fine-Tuning (PEFT) techniques across language, vision, ge...
roshinijoga
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Redirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to RickrollsRedirects Unraveled: From Lost Links to Rickrolls
Redirects Unraveled: From Lost Links to Rickrolls
Kritika Garg
 
Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
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__)
  翻译: