0% found this document useful (0 votes)
9 views18 pages

UNIT-2

The document provides a comprehensive overview of functions and exception handling in Python. It covers how to create and call functions, pass arguments, handle exceptions using try-except blocks, and define user-defined exceptions. Additionally, it explains concepts like recursion, return values, and the use of assert statements for error checking.

Uploaded by

randomvln2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

UNIT-2

The document provides a comprehensive overview of functions and exception handling in Python. It covers how to create and call functions, pass arguments, handle exceptions using try-except blocks, and define user-defined exceptions. Additionally, it explains concepts like recursion, return values, and the use of assert statements for error checking.

Uploaded by

randomvln2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

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:

Example
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()
Try it Yourself »

Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Try it Yourself »
Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil", "Refsnes")
Try it Yourself »
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")
Try it Yourself »

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.

This way the function will receive a tuple of arguments, and can access the
items accordingly:

Example
If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Try it Yourself »
Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.


Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


Try it Yourself »
The phrase Keyword Arguments are often shortened to kwargs in Python
documentations.

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.

This way the function will receive a dictionary of arguments, and can access
the items accordingly:

Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")


Try it Yourself »
Arbitrary Kword Arguments are often shortened to **kwargs in Python
documentations.

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:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Try it Yourself »

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.

E.g. if you send a List as an argument, it will still be a List when it reaches
the function:

Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Try it Yourself »

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
Try it Yourself »

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.

Example
def myfunction():
pass
Try it Yourself »

Recursion
Python also accepts function recursion, which means a defined function can
call itself.

Recursion is a common mathematical and programming concept. It means


that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.

Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Try it Yourself »

EXCEPTIONS

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the
try- and except blocks.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
These exceptions can be handled using the try statement:

Example
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")
Try it Yourself »

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:

Example
This statement will raise an error, because x is not defined:

print(x)
Try it Yourself »

Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:

Example
Print one message if the try block raises a NameError and another for other
errors:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Try it Yourself »

ADVERTISEMENT
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:

Example
In this example, the try block does not generate any error:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Try it Yourself »

Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.

Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Try it Yourself »

This can be useful to close objects and clean up resources:

Example
Try to open and write to a file that is not writable:

try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
Try it Yourself »

The program can continue, without leaving the file object open.

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")
Try it Yourself »

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")
Try it Yourself »
Types of exceptions:

Exception Cause of Error

AssertionError Raised when an assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() function hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when the index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits the interrupt key ( Ctrl+C or Delete ).

MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

NotImplementedError Raised by abstract methods.

OSError Raised when system operation causes system related error.

OverflowError Raised when the result of an arithmetic operation is too large to be represented.
Raised when a weak reference proxy is used to access a garbage collected
ReferenceError
referent.

RuntimeError Raised when an error does not fall under any other category.

Raised by next() function to indicate that there is no further item to be


StopIteration
returned by iterator.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TabError Raised when indentation consists of inconsistent tabs and spaces.

SystemError Raised when interpreter detects internal error.

SystemExit Raised by sys.exit() function.

TypeError Raised when a function or operation is applied to an object of incorrect type.

Raised when a reference is made to a local variable in a function or method, but


UnboundLocalError
no value has been bound to that variable.

UnicodeError Raised when a Unicode-related encoding or decoding error occurs.

UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.

UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.

UnicodeTranslateError Raised when a Unicode-related error occurs during translating.

ValueError Raised when a function gets an argument of correct type but improper value.

ZeroDivisionError Raised when the second operand of division or modulo operation is zero.
If required, we can also define our own exceptions in Python. To learn
more about them, visit Python User-defined Exceptions.
We can handle these built-in and user-defined exceptions in Python
using try , except and finally statements. To learn more about them,
visit Python try, except and finally statements.

Python Try Except:

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the
try- and except blocks.

Python - Assert Statement


In Python, the assert statement is used to continue the execute if the
given condition evaluates to True. If the assert condition evaluates
to False, then it raises the AssertionError exception with the specified
error message.

Syntax
assert condition [, Error Message]

The following example demonstrates a simple assert statement.

Example: assert

Copy

x = 10
assert x > 0
print('x is a positive number.')
Output

x is a positive number.

In the above example, the assert condition, x > 0 evalutes to be


True, so it will continue to execute the next statement without any
error.

The assert statement can optionally include an error message string,


which gets displayed along with the AssertionError. Consider the
following assert statement with the error message.

Example: Assert Statement with Error Message

Copy

x = 0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Output

Traceback (most recent call last):


assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed

Above, x=0, so the assert condition x > 0 becomes False, and so it will
raise the AssertionError with the specified message 'Only positive
numbers are allowed'. It does not execute print('x is a positive
number.') statement.

The following example uses the assert statement in the function.

Example: assert

Copy

def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x

n = square(2) # returns 4
n = square(-2) # raise an AssertionError
Output

Traceback (most recent call last):


assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed
Above, square(2) will return 4, whereas square(-2) will raise
an AssertionError because we passed -2.

The AssertionError is also a built-in exception that can be handled


using try-except construct as shown below:

Example: AssertionError

Copy

def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x

try:
square(-2)
except AssertionError as msg:
print(msg)
Output

Only positive numbers are allowed

Above, calling square(-2) will raise an AssertionError, which will be


handled by the except block. The error message in the assert
statement will be passed as an argument to the exception
argument msg, using as keyword.

Thus, the assert statement should generally be used to prevent


possible errors and specify appropriate error messages.

Creating a User-defined Exception


class:
Here we created a new exception class i.e. User_Error. Exceptions need to be derived
from the built-in Exception class, either directly or indirectly. Let’s look at the given
example which contains a constructor and display method within the given class.

Example
Live Demo

# class MyError is extended from super class Exception


class User_Error(Exception):
# Constructor method
def __init__(self, value):
self.value = value
# __str__ display function
def __str__(self):
return(repr(self.value))
try:
raise(User_Error("User defined error"))
# Value of Exception is stored in error
except User_Error as error:
print('A New Exception occured:',error.value)

Output
A New Exception occured: User defined error

Creating a User-defined Exception


class (Multiple Inheritance):
Derived class Exceptions are created when a single module handles multiple several
distinct errors. Here we created a base class for exceptions defined by that module.
This base class is inherited by various user-defined class to handle different types of
errors.

Example
Live Demo

# define Python user-defined exceptions


class Error(Exception):
"""Base class for other exceptions"""
pass
class Dividebyzero(Error):
"""Raised when the input value is zero"""
pass
try:
i_num = int(input("Enter a number: "))
if i_num ==0:
raise Dividebyzero
except Dividebyzero:
print("Input value is zero, try again!")
print()

Output
Enter a number: Input value is zero, try again!

Creating a User-defined Exception


class (standard Exceptions):

Runtime error is a built-in class which is raised whenever a generated error does not
fall into mentioned categories. The program below explains how to use runtime error
as base class and user-defined error as derived class.

Example
Live Demo

# User defined error


class Usererror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise Usererror("userError")
except Usererror as e:
print (e.args)

Output
('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')
😊ROCK ’N’
ROLL
GUYS😊

You might also like