Function
Function
Python has rich collections of built-in functions. Still we need user defined function for the following
reasons:
1. Functions help divide a program into modules. This makes the code easier to manage and debug
2. It implements code reuse. To reuse the call, a function needs to be called (invoked)
Name of the function is myfactorial(), function returns a value and it has a formal parameter n.
Function name is myfactorial(). In Python, formal parameter does not have any parameter (this issue
will be discussed later). Function’s return statement serves two purposes:
a) It terminates the function
b) Returns a value to the caller
When a function returns a value, the function may be called (invoked) as:
1. VarName=FunctionName(ActualParaList)
2. print(FunctionName(ActualParaList))
Complete Python script including user defined function myfactorial() with parameter no.
def myfactorial(no): • myfactorial() – user defined function
fact=1 • no – Formal parameter
for k in range(1, no+1):
• Function call is:
fact*=k; f1=myfactorial(n)
return fact f2=myfactorial(n+3)
f3=myfactorial(8)
n=int(input('Input n? ')) print(myfactorial(5))
f1=myfactorial(n) myfactorial(6)
f2=myfactorial(n+3)
• Actual parameter:
f3=myfactorial(8)
1st call – n (variable)
print(f1)
print(f2) 2nd call – n+3 (expression)
print(f3) 3rd call – 8 (constant)
print(myfactorial(5)) 4th call – 5 (constant)
myfactorial(6) 5th call – 6 (constant)
Parameter is used to transfer data between caller and user defined function. The data transfer can be either
one-way or it can be two ways. Parameter used in the function header is called formal parameter.
Parameter used during the function call is called actual parameter. Formal parameter receives value from
actual parameter. Data type of formal parameter depends on data type of actual parameter. As shown in
the above example, actual parameter can either be a variable or an expression or a constant. But formal
parameter is a variable. When invoking a function list of actual parameters must be equal to list of formal
parameters. List of actual parameters must be compatible with list of formal parameters.
def add(a, b): First call to function has two int as actual parameters, values stored
t=a+b two format parameters are added and their sum is displayed. Second
print(t) call to function has an int and a float (int and float can be added) as
actual parameters and their sum is displayed. Third call to function has
add(20,20) #call #1 two float actual parameters and their sum is displayed. Fourth call to
add(10,15.5) #call #2 function has two str (two strings are concatenated) as actual parameters
add(5.7,8.8) #call #3 and concatenated string is displayed. Fifth call to function has an int
add('DP','S') #call #4 and a str as actual parameters and they are not compatible hence run-
add(20,'DPS') #call #5 time error. Sixth call to function has a str and a float as actual
add('DPS',5.3)#call #6 parameter and they are not compatible hence run-time error. Seventh
add(40) #call #7 call and eight call to function, number of actual parameter(s) does not
add(23,45,64) #call #8 match with number formal parameters and hence run-time error.
Variable that are declared inside a function body (block) have a local scope, and a variable declared outside
(either after or before) have a global scope. This means that local variable can be accessed only inside the
function in which they are declared, whereas global variable can be accessed throughout the Python script
(anywhere in the program). When a function is called, the variable declared inside its body is brought into
scope.
Variables x and y are global variables since
x=60 #x Global variable variable x is declared before function add()
def add(m, n): and variable y is declared after function add().
z=m+n #z Local variable Variables x and y can be used anywhere in the
print(x,y,z) #Displays 60 DPS 30 Python script – anywhere in the program.
y='DPS' #y Global variable Variable z is a local variable created inside the
add(10, 20) function add() – variable z can be used inside
print(x,y) #Displays 60 DPS the function add() only.
What happens when a local variable is accessed outside its scope? To answer the question a small Python
script will is given below:
Keyword global
As discussed earlier, a global variable can be accessed through out the program. But this may not be true
always. Let us write a small Python script to see what happens.
x=10 The output seems little strange. Function foo() did not update global
def foo(): variables x and y. A global variable can be accessed anywhere in the script
x=100 (program) but global variable cannot be updated in inside a function. In our
y=200 example, function foo() did not update global variables x and y. This is
print(x,y)
because, statement x,y=100,200 creates two local variables x and y. The
y=20
statement print(x,y) displays the local variables x and y. But Inside the
print(x,y)
foo() caller, print(x,y) displays global variables x and y. So the question is
print(x,y) how to update global variables x and y inside the function foo()?
By using the keyword global, we can update one can update a global variable. Edited Python script is
given below with the keyword global.
FAIPS, DPS Kuwait Page 3 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
x=10 x=10
def foo(): def foo():
global x, y x, y=100, 200 #Syntax error
x, y=100, 200 global x, y
print(x,y) print(x,y)
y=20 y=20
foo() foo()
print(x,y) print(x,y)
Running of the Python script produces following Running of the Python script produces syntax error
outputs: because keyword global is used after the statement
100 200 x, y=100, 200
100 200 Keyword global to be used before the updation.
The keyword global, will make variables x and y as global variable and hence the variables x and y can
be updates inside the function foo(). The keyword global is to be used before accessing or updating the
global variables x and y. Without using the keyword global, variable created inside a function with same
name as a global variable, becomes the local variable.
x=10 x=10
def foo(): def foo():
global x global y
x, y=100, 200 x, y=100, 200
print(x,y) print(x,y)
y=20 y=20
foo() foo()
print(x,y) print(x,y)
Running of the Python script produces following Running of the Python script produces following
outputs: outputs:
100 200 100 200
100 20 10 200
Variable x is global variable and variable y is a local Variable y is global variable and variable x is a local
variable. Global variable x is updated. variable. Global variable y is updated.
Keyword global has to be used in every function where a global variable is to be updated.
x=10 x=10
def foo(): def foo():
global x global x
x=100 x=100
print(x) print(x)
def moo(): def moo():
x=1000 #x is local to moo() global x
print(x) x=1000
foo() print(x)
print(x) foo()
moo() print(x)
print(x) moo()
print(x)
Running of the Python script produces following Running of the Python script produces following
outputs: outputs:
100 100
100 100
1000 1000
100 1000
Without the keyword global, x is a local to moo() Because of the keyword global in the function
and hence global variable x does not get updated. moo(), global variable x get updated.
FAIPS, DPS Kuwait Page 4 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
Keyword global can be used to create a global variable inside a user defined function.
x=10 Global variable x=10 is created right in the beginning. Inside
def foo(): the function foo(), global variable y is created. Inside the
global x, y function foo(), global variable x is 100 and global variable y
x, y=100,200 is 100. Function print(x,y) after foo() displays 100
print(x,y)
100. Inside the function moo(), global variable x is 1000 and
def moo():
global variable y is 1000. Function print(x,y) after foo()
global x, y
x, y=1000,2000 displays 1000 1000.
print(x,y) Running of the Python script produces following outputs:
print(x) 10
foo() 100 200
print(x,y) 100 200
moo() 1000 2000
print(x,y) 1000 2000
By using global variable inside a function, one can eliminate use of formal parameter in a function.
def chkarmstrong(): def chkpalindrome():
global n global n
s, t, power=0, n, len(str(n)) s, t=0, n
while t: while t:
d=t%10 d=t%10
s+=d**power s=10*s+d
t//=10 t//=10
if s==n: if s==n:
print('Armstrong') print('Palindrome')
else: else:
print('Not Armstrong') print('Not Palindrome')
n=int(input('Input n? ')) n=int(input('Input n? '))
chkarmstrong() chkpalindrome()
In Python there is no strict data type for any variable. Value stored in an actual argument decides data
type of the formal argument. Hence last two calls to function display() are syntactically correct but
logically wrong. To eliminate this kind of logical error we need Keyword argument. Using Keyword
Argument, formal argument's names are included with the actual arguments. Keyword arguments is
nothing but the list of actual arguments (formal argument names are assigned values during the function
call). Using keyword arguments, the list of actual arguments can be in any order but correct values will
be assigned to the list of formal arguments. An example is given below:
Above example shows that using keyword arguments, even if the order of actual arguments does not
match with order of formal arguments but correct values are assigned to the formal arguments.
As mentioned earlier, default arguments start from right. Examples of incorrect use of default arguments
are given below:
def foo(a=10,b,c=30): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal argument b is non-default argument. Possible solution,
print(avg) make formal argument b as default argument.
def foo(a=10,b=20,c): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal argument c is non-default argument. Possible solution,
print(avg) make parameter c as default argument.
def foo(a=10,b,c): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal arguments b and c are non-default arguments. Possible
print(avg) solution, make formal argument b and c as default argument.
def foo(a,b=20,c): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal argument c is non-default argument. Possible solution,
print(avg) make formal argument c as default argument.
FAIPS, DPS Kuwait Page 10 / 10 ©Bikram Ally