Unit 3 Functions
Unit 3 Functions
Functions
Output:
Olga Puchma
Puchma, Olga
Variable arguments
• The special syntax *args in function definitions in python is used to pass a
variable number of arguments to a function. It is used to pass a non-
keyworded, variable-length argument list.
• The syntax is to use the symbol * to take in a variable number of arguments;
by convention, it is often used with the word args.
• *args allows you to handle more arguments than the number of formal
arguments that you previously defined. With *args, any number of extra
arguments can be tacked on to your current formal parameters (including zero
extra arguments).
• For example : we want to make a multiply function that takes any number of
arguments and able to multiply them all together. It can be done using *args.
• Using the *, the variable that we associate with the * becomes an iterable
meaning you can do things like iterate over it, run some higher order functions
Cntd…
• Example-1:
def myFun(*args):
for ar in args:
print (ar)
myFun('Hello', 'Welcome', 'to', 'Python Programming')
Output:
Hello
Welcome
to
Python Programming
Cntd…
• Example-2:
def myFun(arg1, *args):
print ("First argument :", arg1)
for ar in args:
print("Next argument through *args :", ar)
myFun('Hello', 'Welcome', 'to', ‘Python class’)
Output:
First argument : Hello
Next argument through *args : Welcome
Next argument through *args : to
Next argument through *args : Python class
Variable keyword arguments
• The special syntax **kwargs in function definitions in python is used to
pass a keyworded, variable-length argument list. We use the name kwargs
with the double star. The reason is, ‘**’ allows us to pass through any
number of keyword arguments.
• A keyword argument is where you provide a name to the variable as you pass
it into the function.
• One can think of the kwargs as being a dictionary that maps each keyword to
the value that we pass along side it. That is why when we iterate over the
kwargs there doesn’t seem to be any order in which they were printed out.
Cntd…
• Example:
def myFun(**kwargs):
for key,value in kwargs.items():
print (key,value)
myFun(first ='Python', mid ='for', last='developers')
Output:
first Python
mid for
last developers
Cntd…
• Example-2:
def myFun(arg1, **kwargs):
print (arg1)
for key, value in kwargs.items():
print (key, value)
myFun("Hi", first ='programmers', mid ='of', last='Python')
Output:
Hi
first programmers
mid of
last Python
Recursion
• When a function calls itself repeatedly, is called as recursion
• There are 2 components of recursion:
1) Base case: It directly specifies, result of a special case
2) Recursive (inductive) case: It calls the same function with some different value.
• Simple example of recursion is factorial numbers:
• 1 != 1 base case
• (n+1)!= (n+1) * n! It defines all other cases except base case (recursive case)
• Remember: Each function defines a new name space, also called a scope of
function.
Factorial function: iterative vs recursive
• Iterative program: vs Recursive version:
def facto(n): def facto(n):
result=1 if n==1:
return 1
while(n>1):
else:
result= result*n return n*facto(n-1)
n=n-1 print(facto(5))
return result
print(facto(5)) Output:120
Output: 120
Fibonacci series: iterative & recursive
• Try yourself: Iterative program vs Recursive program
def fib(n): def fib(n):
i=0; j=1 if n==0 or n==1:
print(i,j,end=" ") return n
for t in range(n): else:
temp=j return fib(n-1)+fib(n-2)
j=i+j
i=temp def fib_num(n):
print(j, end=" ") for i in range(n+1):
return j print (fib(i))
fib(5) fib_num(5)
Output: 0 1 1 2 3 5 8 Output: 0 1 1 2 3 5
• H.W. : Check whether given string is palindrome or not using recursion
Global vs Local vs Nonlocal variable
• A variable declared outside of the function or in global scope is known as
global variable. Global variable can be accessed inside or outside of the
function.
• A variable declared inside the function's body or in the local scope is known
as local variable.
• Consider following examples:
1) def f():
print(s)
s="I like python"
f()
Output: I like python
Cntd…
2) def f():
s="local"
print(s)
f()
print(s)
Output: local
NameError: name 's' is not defined
3) def f():
s="local"
print(s)
s="I like python."
f()
print(s)
Output: local
Cntd…
4) def f():
print(s) # This line produce an error
s="local“
s="I like python."
f()
print(s)
Output: 42 17 4 17
Nonlocal variable
• Nonlocal variable are used in nested function whose local scope is not defined. This means, the variable
can be neither in the local nor the global scope.
• 'nonlocal' keyword is used to create nonlocal variable.
Example:
def outer():
x = "local" In this code there is a nested function inner(). The inner()
def inner(): function is defined in the scope of function outer().
nonlocal x We use nonlocal keyword to create nonlocal variable. That
x = "nonlocal" means, no separate copy of ‘x’ for inner() is created, it modifies
print("inner:", x) ‘x’ of outer().
inner()
print("outer:", x) Note : If we change value of nonlocal variable, the changes
outer() appear in the local scope too.
Output:
inner: nonlocal
outer: nonlocal
lambda function
• Lambda function is a function that is defined without a name. lambda
functions are also called anonymous functions.
• While normal functions are defined using the def keyword, anonymous
functions are defined using the lambda keyword.
• A lambda function can take any number of arguments, but can only have one
expression.
• Syntax- lambda arguments: expression
• Example:
double = lambda x: x * 2
print(double(5))
Output: 10
filter() function
• The filter() function in Python takes in a function and a list as arguments.
• The function is called with all the items in the list and a new list is returned
which contains items for which the function evaluates to True.
• Example:
li=[1,2,3,4]
x=list(filter(lambda t: t%2==0,li))
print(x)
Output: [2, 4]
map() function
• The map() function in Python takes in a function and a list.
• The function is called with all the items in the list and a new list is
returned which contains items returned by that function for each item.
• Example:
li = [5, 7, 22, 97, 62]
final_list = list(map(lambda x: x*2 , li))
print(final_list)
Output: [10, 14, 44, 194, 124]
reduce() function
• The reduce() function takes a function and a list as argument.
• The function is called with a lambda function and a list. A new reduced
result is returned. It performs a repetitive operation over the pairs of the
list.
• reduce() is a part of functools module. You have to import that module to
use reduce() function.
• Example:
from functools import *
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)
Output: 193
Function as objects
• In Python, functions are first-class objects. That means that they can
be treated like objects of any other type, e.g., int or list.
• Functions have types, e.g., the expression type(fact) has the value
<type 'function'>; they can appear in expressions, e.g., as the right-
hand side of an assignment statement or as an argument to a function;
they can be elements of lists; etc.
• Using functions as arguments can be particularly convenient in
conjunction with lists. It allows a style of coding called higher-order
programming.
• Function that take other functions as arguments are also called higher
order functions.
• Example:
def applyToEach(L, f):
"""Assumes L is a list, f a function
Mutates L by replacing each element, e, of L by f(e)"""
for i in range(len(L)): Specification (docstring)
L[i] = f(L[i])
L = [1, -2, 3.33]
print ('L =', L)
print ('Apply abs to each element of L.') Output:
applyToEach(L, abs) L = [1, -2, 3.33]
Apply abs to each element of L.
print ('L =', L) L = [1, 2, 3.33]
print('Apply int to each element of L.’) Apply int to each element of L.
applyToEach(L, int) L = [1, 2, 3]