Tuesday 3 December 2019

Passing Parameters

Parameters in Function:


#passing an value to a function (Immutable)
def modify(a):
    a=25
    print(a,id(a))
a=10
modify(a)
print(a,id(a))
"""output:
25 1578031664
10 1578031424
>>>
"""
We know that In python integers, floats, strings and tuples are immutable. Means their data can not be modified but in the other hand lists and dictionaries are mutable

Ex2: lists, dictionaries are Mutable
#passing an value to a function
def modify(a):
    a.append(25)
    print(a,id(a))
a=[10,20,30]
modify(a)
print(a,id(a))
"""output:
[10, 20, 30, 25] 56411560
[10, 20, 30, 25] 56411560
>>>
"""
Values are passed to functions by object references. If the object is immutable, the modified value is not available outside the function and if the object is mutable, its modified version is available outside the function.

#A python program to create a new object inside the function does not modify outside obj
def modify(a):
    """to create a new list"""
    a=[10,11,12]
    print(a,id(a))
#function call
a=[1,2,3,4]
modify(a)
print(a,id(a))
"""
output:
inside the function: [10, 11, 12] 51496240
outside the function:[1, 2, 3, 4] 51496560
>>> """

# function defn

def example(name):

    print(name, "good morning")

 

example("Ganga")#function call

example("Venu")

example("krishna")

 

If we are passing the parameters (value/variable/data/information) to the function.

It is passed to the function which is specified in the parenthesis

We can give any number of parameters to the function, we have to separate with comma operator.

 

 

def add(a,b):

    c=a+b

    print(c)

   

#reading the input values

a=int(input("enter a value"))

b=int(input("enter b value"))

add(a,b) #function call

 

we can pass number of parameters to the functions

def add(a,b):

    c=a+b

#    print(c)

    return c

#reading the input values

a=int(input("enter a value"))

b=int(input("enter b value"))

print(add(a,b)) #function call

#defining the function

#call by reference

def modify(b):

    #print("list values are=",a)

    #appending the values to the list

    b.append(50)

    b.append(60)

    print(b)

a=[10,20,30,40]#list is created

#passing immutable(list) object

modify(a)#function call

Call by Reference:

Whatever changes are done in the function, it is reflected to the actual parameter.

 #passing a string to the function

def name(s):

    s="Hello "+s

    print(s)

s="How are you"

name(s)



Related Video: https://youtu.be/JhTtHTdP2SA
Next: Formal and actual parameters
Prev: A function return more than one value

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...