Functions
Functions
Functions
Gaurav Sharma
9971677014
Index
4. Default Arguments………………………………………………..……………4
5. Keyword Arguments…………………………………………………….……..4
7. Anonymous functions………………………………………………………….5
Page 1
Functions in Python
In Python, function is a group of related statements that perform a specific task.
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 code reusable. There are four types of functions in Python:
I. Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to print an object to
the terminal etc.
II. Function defined in modules like random, maths etc.
III. User-Defined Functions (UDFs), which are functions that users create to help them out; And
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
return
A simple example
def evenOdd( x ): # x is parameter
”””A simple Python function to #docstring
check whether x is even or odd ”””
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code
a=10
evenOdd(a) #function calling a is argument
evenOdd(3) #function calling
Output:
even
odd
Page 2
Docstring
The first string after the function header is called the docstring and is short for documentation string. It is used to
explain in brief, what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had for
dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally use triple quotes
so that docstring can extend up to multiple lines. This string is available to us as __doc__ attribute of the function.
For example:
>>> print(evenOdd.__doc__)
A simple Python function to
check whether x is even or odd
Note: The parameter required by a function i.e. which has/have to be passed to the function while calling are
called positional or required arguments. In above evenOdd( ) example, x is a positional argument. You can’t
skip or change the order of these arguments.
Output:
[20, 11, 12, 13, 14, 15]
Page 3
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]
Default arguments:
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.
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:
The idea behind Keyword argument is to allow caller to specify argument name with values so that caller does not
need to remember order of parameters.
# Keyword arguments
student(firstname =’Raman’, lastname ='Singh')
student(lastname ='Singh', firstname ='Raman')
Output:
('Raman', 'Singh')
('Raman', 'Singh')
Page 4
Variable length arguments:
We can have variable number of arguments. Please see this for details.
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is ", res)
res = is_true(2<5)
print("\nResult of is_true function is ", res))
Output:
Result of add function is 5
Result of is_true function is True
In Python, you can return multiple values by simply return them separated by commas. See a simple example below
def test():
return 'abc', 100 #Note: comma-separated values are considered tuples without parentheses
result = test()
print(result)
Page 5
print(type(result))
Output:
('abc', 100)
<class 'tuple'>
You can unpack and assign multiple return values to different variables.
a, b = test()
print(a)
print(b)
Output:
abc
100
Scope: A scope defines the hierarchical order in which the namespaces have to be searched in order to obtain the
mappings of name-to-object(variables). It is a context in which variables exist and from which they are referenced. It
defines the accessibility and the lifetime of a variable.
pi = 'outer pi variable'
def print_pi():
pi = 'inner pi variable'
print(pi)
print_pi()
print(pi)
Output:
inner pi variable
outer pi variable
Above program give different outputs because the same variable name pi resides in different namespaces, one
inside the function print_pi and the other in the upper level. When print_pi() gets executed, ‘inner pi variable‘ is
printed as that is pi value inside the function namespace. The value ‘outer pi variable‘ is printed when pi is
referenced in the outer namespace. From the above example, we can guess that there definitely is a rule which is
followed, in order in decide from which namespace a variable has to be picked.
Page 6
In Python, the LEGB rule is used to decide the order in which the namespaces are to be searched for scope
resolution. The scopes are listed below in terms of hierarchy(highest to lowest/narrowest to broadest):
Local Scope:
Local scope refers to variables defined in current function. Always, a function will first look up for a variable name in
its local scope. Only if it does not find it there, the outer scopes are checked.
# Local Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)
inner()
Output:
inner pi variable
On running the above program, the execution of the inner function prints the value of its local (highest priority in
LEGB rule) variable pi because it is defined and available in the local scope.
# Global Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)
inner()
print(pi)
Output:
inner pi variable
global pi variable
Therefore, as expected the program prints out the value in the local scope on execution of inner(). It is because it is
defined inside the function and that is the first place where the variable is looked up. The pi value in global scope is
printed on execution of print(pi) on line 9.
# Enclosed Scope
pi = 'global pi variable'
def outer():
pi = 'outer pi variable'
def inner():
print(pi)
inner()
Page 7
outer()
print(pi)
Output:
outer pi variable
global pi variable
The pi variable is not found in local scope, so the higher scopes are looked up. It is found in both enclosed and global
scopes. But as per the LEGB hierarchy, the enclosed scope variable is considered even though we have one defined
in the global scope.
# Built-in Scope
from math import pi
# pi = 'global pi variable'
def outer():
# pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
print(pi)
inner()
outer()
Output:
3.141592653589793
Since, pi is not defined in either local, enclosed or global scope, the built-in scope is looked up i.e the pi value
imported from math module. Since the program is able to find the value of pi in the outermost scope, the following
output is obtained,
Page 8