Professional Documents
Culture Documents
FUNCTION
SANOSH KUMAR
PGT COMPUTER SCIENCE
Is Python call by reference or call by
value
Python utilizes a system, which is known as “Call by Object
Reference” or “Call by assignment”. In the event that you
pass arguments like whole numbers, strings or tuples to a
function, the passing is like call-by-value because you can
not change the value of the immutable objects being passed
to the function. Whereas passing mutable objects can be
considered as call by reference because when their values are
changed inside the function, then it will also be reflected
outside the function.
Python code to demonstrate
# call by value
string = "Geeks"
def test(string):
string = "GeeksforGeeks"
print("Inside Function:", string)
# Driver's code
test(string)
print("Outside Function:", string)
Python code to demonstrate call by
reference
def add_more(list):
list.append(50)
print("Inside Function", list)
# Driver's code
mylist = [10,20,30,40]
add_more(mylist)
print("Outside Function:", mylist)
*args OR **kwargs
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
def myFun(arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
2.)**kwargs
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 because the double
star allows us to pass through keyword arguments (and any number of
them).
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='Geeks', mid ='for', last='Geeks')
def myFun(arg1, **kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun("Hi", first ='Geeks', mid ='for', last='Geeks')