Unit 4
Unit 4
By:
Prof. Mani Butwall,
Asst. Prof. (CSE)
Contents
• Functions
• Defining a function
• calling a function
• Types of functions
• Function Arguments
• Anonymous functions
• Keyword and Optional Parameters
• Local and global variables
• Defining recursion and its application
• programming through recursion
• Passing Collection to a function
Function
• A function is a set of statements that take inputs, do some
specific computation and produces output. The idea is to put
some commonly or repeatedly done task together and make a
function, so that instead of writing the same code again and
again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can
also create your own functions. These functions are called
user-defined functions.
• Functions help break our program into smaller and modular
chunks. As our program grows larger and larger, functions
make it more organized and manageable.
• Furthermore, it avoids repetition and makes the code
reusable.
Syntax
• Above shown is a function definition that consists of the following
components.
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function.
They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the
function does.
• One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually 4
spaces).
• An optional return statement to return a value from the function.
Example
• def greet(name):
• """ This function greets to the person passed in as a parameter
"""
• print("Hello, " + name + ". Good morning!")
print(absolute_value(2))
print(absolute_value(-4))
How Function Works
Scope and Lifetime of Variables
• Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the
variable is recognized. Parameters and variables defined inside
a function are not visible from outside the function. Hence,
they have a local scope.
• The lifetime of a variable is the period throughout which the
variable exits in the memory. The lifetime of variables inside a
function is as long as the function executes.
• They are destroyed once we return from the function. Hence,
a function does not remember the value of a variable from its
previous calls.
• Here is an example to illustrate the scope of a variable inside a
function.
• Here, we can see that the value of x is 20 initially. Even though
the function my_func() changed the value of x to 10, it did not
affect the value outside the function.
• This is because the variable x inside the function is different
(local to the function) from the one outside. Although they
have the same names, they are two different variables with
different scopes.
• On the other hand, variables outside of the function are
visible from inside. They have a global scope.
• We can read these values from inside the function but cannot
change (write) them. In order to modify the value of variables
outside the function, they must be declared as global variables
using the keyword global.
Types of Functions
• Basically, we can divide functions into the following two types:
1. Built-in functions- Functions that are built into Python.
2. User-defined functions- Functions defined by the users
themselves.
Parameter Passing in Python
• Pass by Reference or pass by value?
One important thing to note is, in Python every variable name is a
reference. When we pass a variable to a function, a new reference
to the object is created. Parameter passing in Python is same as
reference passing in Java.
• # Here x is a new reference to same list lst
• def myFun(x):
• x[0] = 20
•
• # Driver Code (Note that lst is modified
• # after function call.
• lst = [10, 11, 12, 13, 14, 15]
• myFun(lst);
• print(lst)
• Output: [20, 11, 12, 13, 14, 15]
• When we pass a reference and change the received reference to
something else, the connection between passed and received
parameter is broken. For example, consider below program.
• def myFun(x):
•
• # After below line link of x with previous
• # object gets broken. A new object is assigned
• # to x.
• x = [20, 30, 40]
•
• # Driver Code (Note that lst is not modified
• # after function call.
• lst = [10, 11, 12, 13, 14, 15]
• myFun(lst);
• print(lst)
• Output: [10, 11, 12, 13, 14, 15]
• Another example to demonstrate that reference link is broken if we
assign a new value (inside the function).
• def myFun(x):
•
• # After below line link of x with previous
• # object gets broken. A new object is assigned
• # to x.
• x = 20
•
• # Driver Code (Note that lst is not modified
• # after function call.
• x = 10
• myFun(x);
• print(x)
• Output: 10
Default Arguments
• Default argument:
A default argument is a parameter that assumes a default value if a
value is not provided in the function call for that argument. The
following example illustrates Default arguments.
• # Python program to demonstrate
• # default arguments
• def myFun(x, y=50):
• print("x: ", x)
• print("y: ", y)
•
• # Driver code (We call myFun() with only
• # argument)
• myFun(10)
• Output:('x: ', 10) ('y: ', 50)
• Like C++ default arguments, any number of arguments in a
function can have a default value. But once we have a default
argument, all the arguments to its right must also have default
values.
Keyword Arguments
• Keyword arguments:
The idea is to allow caller to specify argument name with
values so that caller does not need to remember order of
parameters.
• # Python program to demonstrate Keyword Arguments
• def student(firstname, lastname):
• print(firstname, lastname)
•
• # Keyword arguments
• student(firstname =‘Mani', lastname =‘Butwall')
• student(lastname =‘Butwall', firstname =‘Mani')
• Output:(‘Mani', ‘Butwall') (‘Mani', ‘Butwall')
Variable Length Arguments
• Variable length arguments:
We can have both normal and keyword variable number of
arguments.
• # Python program to illustrate
• # *args for variable number of arguments
• def myFun(*argv):
• for arg in argv:
• print (arg)
•
• myFun('Hello', 'Welcome', 'to', ‘Python')
• Output:Hello Welcome to Python
Example
• # Python program to illustrate
• # *kargs for variable number of keyword arguments
•
• def myFun(**kwargs):
• for key, value in kwargs.items():
• print ("%s == %s" %(key, value))
•
• # Driver code
• myFun(first ='Geeks', mid ='for', last='Geeks')
• Output:last == Geeks mid == for first == Geeks
Anonymous Functions
• Anonymous functions: In Python, anonymous function means
that a function is without a name. As we already know that
def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions.