Functions
Functions
INTRODUCTION
A function is a programming block of codes which
is used to perform a single, related task. It only runs
when it is called. We can pass data, known as
parameters, into a function. A function can return
data as a result.
a, b, x, y = 1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in
parameter x and y of function fun()
print(a, b, x, y)
OUTPUT :-
10 30 100
50
VARIABLE’S SCOPE IN FUNCTION
E.g.
x = lambda a, b : a * b
print(x(5, 6))
OUTPUT:
30
Mutable/immutable
properties
of data objects w/r
function
Immutable objects:
Mutable objects: int, set,
list, dict, float,
bytecomplex,
array string, tuple,
frozen
set ,bytes
MUTABLE/IMMUTABLE PROPERTIES OF DATA OBJECTS
W/R FUNCTION
How objects are passed to
#Pass by reference Functions #Pass by value
def updateList(list1): def updateNumber(n):
print(id(list1)) print(id(n))
list1 += [10] n += 10
print(id(list1)) print(id(n))
n = [50, 60] b =5
print(id(n)) print(id(b))
updateList(n) updateNumber
print(n) (b) print(b)
print(id(n)) print(id(b))
OUTPUT OUTPUT
34122928 1691040064
34122928 1691040064
34122928 1691040224
[50, 60, 10] 5
34122928 1691040064
#In above function list1 an object is being passed #In above function value of variable b is
and its contents are changing because it is not being changed because it is immutable
mutable that’s why it is behaving like pass by that’s why it is behaving like pass by value
reference
PASS LIST TO FUNCTION
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change
the same list that the argument is referencing.
e.g. OUTPUT:
def 1
dosomething( thelist ): 2
3
for element in thelist: red
print (element) green
dosomething( ['1','2','3'] ) Blue
Note:- List is mutable datatype that’s why it
alist = ['red','green','blue'] treat as pass by reference.It is already explained
dosomething( alist ) in topic Mutable/immutable properties of data
objects w/r function
PASS STRING TO A FUNCTION
r="Mohan"
OUTPUT
welcome(r) Mohan
print(r)
PASS TUPLE TO A FUNCTION
in function call, we have to explicitly define/pass the tuple.It
is not required to specify the data type as tuple in formal
argument.
E.g.
def Max(myTuple):
first, second =
myTuple if
first>second:
return first
else:
return
r=(3,second
1) OUTPUT
m=Max(r) 3
print(m)
PASS DICTIONARY TO A FUNCTION