Functions GRD 12
Functions GRD 12
ACTUAL PARAMETERS
Formal parameters are given within function header and actual parameters are
mentioned in the function call statement and can be constants, variables,
symbols or expressions
Specifying names for the values being passed, in the function call is
known as Keyword arguments.
Ex 1:- positional/ required argument
def interest(principal,time,rate):
return (principal*time*rate)/100
X=interest(p,t,r)
The order and number of arguments in the function call should match with the
order and number of parameters in the function header.
Ex 2:- default argument within a function header allows to skip arguments at
the time of function call . In a function header non-default arguments
cannot follow default argument.
def interest(principal,time=2,rate=0.10):
return principal*time*rate
X=interest(p) or x=interest(p,6
Ex 3:- The Specifying of names to the values being passed, in the function call
is known as Keyword Arguments.
def interest(time=2,prin=3000,rate=0.12)
Rules for combining all three types of
arguments
Python states that in a function call statement:
• An argument list must first contain positional
(required) arguments followed by any
keyword argument
• Keyword arguments should be taken from the
required arguments preferably
• You cannot specify a value for an argument
more than once
For instance consider the following function header:
def int(prin,cc,time=2,rate=0.09):
return print*time*rate
Int(prin=3000,cc=5)
Int(rate=0.12,prin=5000,cc=4)
Int(cc=4,rate=0.12,prin=5000)
Int(5000,3,rate=0.05)
Int(rate=0.05,5000,3)
Int(5000,prin=300,cc=2)
Int(5000,principal=300,cc=2)
Int(500,time=2,rate=0.05)
Variable length arguments
In Python, we can pass a variable number or
variable length of arguments to a function using
special symbols. There are two special symbols:
• *args (Non Keyword Arguments)
• **kwargs (Keyword Arguments)
*args
def calcsum(x,y):
s=x+y # 8
print(s)
return s
n1=int(input(“enter first num:”)) # 5
n2=int(input(“enter second num:”)) # 3
sum=calcsum(n1,n2)
print(sum)
Output:-
5
8
Output:
95
15
95
The underlined statement will create a local variable as it is assignment statement. It won’t
refer to tigers of main program
To use Global variable inside local scope
def state1():
global tigers
tigers=15
print(tigers)
tigers=95
print tigers
state1()
print(tigers)
Output:
95
15
15
The Underlined statement is an indication not to create local variable with the
name tigers, rather use global variable tigers.
The global statement is a declaration which holds for
the entire current code block it means that the listed
identifiers are part of the global environment.
The global statement cannot be reverted in a program
run. One should avoid using global statement in
python program.
Although global variables can be accessed through
local scope, but it is not a good programming
practice. So, keep global vatiables global, local
variables local.