0% found this document useful (0 votes)
3 views42 pages

Unit-4 (Python Functions & Exceptions)

Uploaded by

xperixolo9
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)
3 views42 pages

Unit-4 (Python Functions & Exceptions)

Uploaded by

xperixolo9
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

PYTHON FUNCTIONS

Types of Functions

• Functions can be divided into the following two types:

• Built-in functions - Functions that are built into Python. Ex:


all(),any()

• User-defined functions - Functions defined by the users


themselves.
Functions in Python
• A function is a set of statements that take inputs, do
some specific computation and produces output.
• Python provides built-in functions like print(), etc.
but we can also create your own functions. These
functions are called user-defined functions.
• Syntax:
def function_name(parameters):

statement(s)
• def - Keyword & start of the function header
• function name - uniquely identify the function.
• Parameters (arguments) through which we pass values to a
function. (optional)
• A colon (:) - end of the function header.
• Statements must have the same indentation level (usually 4
spaces).
• An optional return statement to return a value from the
function.
Scope and Lifetime of variables
• Parameters and variables defined inside a function are not visible
from outside the function. Hence, they have a local scope.
• In order to modify the value of variables outside the function, they
must be declared as global variables using the keyword global.
Example:
def my_func():
x = 10 # local to the function block
print("Value inside function:",x) # Value inside function: 10

//x = 20 #global scope


my_func()
print("Value outside function:",x) #Value outside function: 20
• Example:
def evenOdd( x ):
if (x % 2 == 0): -→ Function Definition
print ("even“)
else:
print ("odd“)
evenOdd(2) # even -→ Function call
evenOdd(3) # odd
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.
• Arguments are often shortened to args in Python documentations.

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

my_function("John“) #Welcome John


my_function("vicky") #Welcome vicky
my_function("Riya") #Welcome Riya
Number of Arguments
• A function must be called with the correct number of
arguments
Example
def my_function(fname, lname):
print(fname + " " + lname) # Rahul Dravid

my_function(“Rahul", “Dravid")

my_function(lname=“Rahul”, fname=“Dravid”) #Dravid Rahul


Arbitrary Arguments, (*args)
• When the number of arguments are not known, 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:
def my_function(*kids):
print("The Eldest child is " + kids[0])

my_function("Dhoni", "Kohli", "Rohit") # The Eldest child is Dhoni


Keyword Arguments:
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
• The phrase Keyword Arguments are often shortened to kwargs in Python
documentations.

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

my_function(child1 = “Dhoni", child2 = “Dravid” ,child3 = “Jadeja")


Arbitrary Keyword Arguments, **kwargs
• When the number of kwargs are not known, 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.
• Arbitrary Keyword Arguments are often shortened to **kwargs in
Python documentations.
Example:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = “Hardik", lname = “Pandya")


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")
Passing a List as an Argument
If we 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)
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)) # 15
print(my_function(5)) # 25
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 pass statement can be used to avoid getting
error
Example:
def myfunction():
pass
Recursion
Python also accepts function recursion, which means a defined function can
call itself.

Example:
def tri_recursion(k):
if(k > 0):
result = tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Python Lambda
• In Python, an anonymous function is a function that is defined without a
name.

• While normal functions are defined using the def keyword in Python,
anonymous functions are defined using the lambda keyword.

• Hence, anonymous functions are also called lambda functions

• Every anonymous function you define in Python will have 3 essential parts:
– The lambda keyword.
– The parameters (or bound variables), and
– The function body
Syntax
lambda arguments : expression
Example:
double = lambda x: x * 2
print(double(5))
lambdas in filter()
• The filter function is used to select some particular elements
from a sequence of elements. The sequence can be any
iterator like lists, sets, tuples, etc.
• The elements which will be selected is based on some pre-
defined constraint. It takes 2 parameters:
• A function that defines the filtering constraint
• A sequence (any iterator like lists, tuples, etc.)
• For example,
sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = filter (lambda x: x > 4, sequences)
print(list(filtered_result))
lambdas in map()

• the map function is used to apply a particular operation to


every element in a sequence. Like filter(), it also takes 2
parameters:
• A function that defines the op to perform on the elements
• One or more sequences
• For example,
sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = map (lambda x: x*x, sequences)
print(list(filtered_result))
Exception Handling
Find the output
• Example:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a / b;
print("a/b = %d" % c)

# other code:
print("Hi I am other part of the program")
Exceptions
• An exception can be defined as an abnormal
condition in a program resulting in the disruption
in the flow of the program.
• Whenever an exception occurs, the program halts
the execution, and thus the further code is not
executed.
• So, the exception handling is the way to handle
the Exception so that the other part of the code
can be executed without any disruption.
Common Exceptions
• A list of common exceptions that can be
thrown from a normal python program is
given below.
Exception Occurrence
ZeroDivisionError Occurs when a number is divided
by zero
NameError Occurs when a name is not found.
It may be local or global
IndentationError If incorrect indentation is given

IOError Occurs when Input Output


operation fails
EOFError Occurs when the end of the file is
reached, and yet operations are
being performed
Keywords(try ,except, finally)
• TRY:
If the python program contains suspicious code that may
throw the exception, we must place that code in the try block.
• EXCEPT:
The try block must be followed with the except statement
which contains a block of code that will be executed if there is
some exception in the try block.
• FINALLY:
The finally block with the try block in which, we can place
the important code which must be executed before the try
statement throws an exception.
Syntax for try and except

try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
syntax for try ,except ,else
try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed
• Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")
Points to remember
1. Python facilitates us to not specify the exception
with the except statement.
2. We can declare multiple exceptions in the except
statement since the try block may contain the
statements which throw the different type of
exceptions.
3. We can also specify an else block along with the
try-except statement which will be executed if
no exception is raised in the try block.
4. The statements that don't throw the exception
should be placed inside the else block.
• Example:
try:
#this will throw an exception if the file doesn't
exist.
fileptr = open("[Link]","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
[Link]()
Declaring multiple exceptions
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception


3>,...<Exception n>)
#block of code

else:
#block of code
• Example:
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
The finally block
• We can use the finally block with the try block in which,
we can pace the important code which must be executed
before the try statement
throws an exception.
• Syntax:
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
• Example:
try:
k = 10 // 0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
• Example:
try:
k = 5 // 1 # No exception raised
print(k)

# intends to handle zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
• Example:
# Exception is not handled
try:
k = 100// 0 # exception raised
print(k)

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Raising exceptions
• An exception can be raised by using the raise
clause in python.
Syntax:
raise Exception_class,<value>
Points to remember
1. To raise an exception, raise statement is used.
The exception class name follows it.
2. An exception can be provided with a value
that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e"
is used as a reference variable which stores
the value of the exception.
• Example:
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
• Example:
try:
a = int(input("Enter a?"))
b = int(input("Enter b?"))
if b is 0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Custom Exception
• The python allows us to create our exceptions
that can be raised from the program and
caught using the except clause.
• Example:
class ErrorInCode(Exception):
def __init__(self, data):
[Link] = data

def __str__(self):
return repr([Link])
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", [Link])

You might also like