Functions in Python - Passing Arguments by Value


Recall: The scope of a variable is the part of the program in which the variable is accessible. The scope of a function's parameter is that function. No statement outside the function can access or refer to the parameter.

In Python, a function cannot change the value of an argument that is passed to it.  We "pass the value" of the argument to the function, but we don't allow the function to modify the argument. The argument's value is stored in the parameter when the function begins running.


Example:

def main():
    arg1 = 35
    print "arg1 is", arg1
    changeIt(arg1)
    print "After function call, arg1 is", arg1

def changeIt(parm):
    # parm initially has the same value as the argument used when
    # the method is called
    parm = -1
    print "parm is", parm

main()  # execute main function

Question: What happens when this program is run??




Note: The situation is different when a list is passed to a function - we will talk more about this soon.



Functions that (appear to) return multiple values


A function can return a tuple, which is a collection of values.

Example:

def divide(a, b):
    # return the result of integer division a/b, and the remainder in a tuple

    return a/b, a%b

def main():
   
    div, rem = divide(13, 8)
    print "%d/%d = %d, with remainder %d!" % (13, 8, div, rem)

    for i in range(1, 16):
       # print results of dividing 15 by i
       div, rem = divide(15, i)
       print "%d/%d = %d, with remainder %d" % (15, i, div, rem)

main()



Question: what is the output?





Exercise: Write a function minMax() that takes 2 arguments, a and b, and returns a tuple containing the minimum and maximum of a and b (in that order). Then write a main function that calls minMax() on all combinations of inputs a and b such that 1<=a, b<= 4.