The document discusses exception handling in Python, explaining the differences between syntax errors and exceptions, along with how to use try, except, else, and finally blocks. It also covers raising exceptions, creating custom exceptions, and the usage of functions, including defining, calling, and passing parameters to them. Additionally, it touches on variable scope, lambda functions, and Python documentation strings (docstrings).
Introduction to exception handling in Python, describing termination on error and types of errors.
Definition of Syntax Errors with examples including typographical errors and incorrect indentation.
Explanation of exceptions, errors during execution, examples, and types such as ZeroDivisionError, NameError.
Demonstration of try-except blocks, usage of else and finally blocks for exception handling.
Technique to handle multiple exceptions and creating custom exceptions to enhance error management.Implementing custom exceptions in nested loops, with examples of exception handling when searching for items.
Introduction to functions, defining, calling, returning values, recursion, lambda functions, and their syntax. Creating lambda forms, documentation strings in Python functions, and their formatting rules.
Exception Handling inPython 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 – SyntaxError • 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 comein 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 blockwill 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 • Youcan 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 canuse 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 finallyblock, 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 isan 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 tryblock 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 anexception • 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 keywordis 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 Exceptionusing “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 CustomException • 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 • Oneuse 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 prettytableimport 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 functionis 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 aFunction • 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.
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 • Youcan 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 Listas 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 • Tolet 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 alsoaccepts 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 referencevs 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.
• # Functiondefinition 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. Localvariables • 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: • InPython, 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
• 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__)