Lesson 10 - Additional Function Topics

The following topics are discussed in this notebook:

  • Variable scope.
  • Multiple return values.

Returning Multiple Values

It is possible for a Python function to return multiple values. To do so, simply list all of the values to be returned within the return statement, separated by commas.

In [1]:
def power(a,b):
    return a**b, b**a

a_to_b,b_to_a = power(2,5)
print(a_to_b)
print(b_to_a)
32
25

� Exercise

Write a function num_divisions() that takes two arguments, div and num, and returns the number of times that div evenly divides num, as well as the remainder of num after factoring out all of the div factors.

In [2]:
def num_divisions(num, div):
    
    temp = num
    count = 0
    
    while(temp % div == 0):
        temp = temp / div
        count += 1
                
    return count, temp
In [3]:
count, rem = num_divisions(900, 2)
print('Count:', count)
print('Remainder:', rem)
Count: 2
Remainder: 225.0
In [4]:
count, rem = num_divisions(6237, 3)
print('Count:', count)
print('Remainder:', rem)
Count: 4
Remainder: 77.0

� Exercise

Write a function called locate. The function should take two arguments: a list called arg_list, and another variable called arg_val.

The function should return two values: A list of indices at which the element in arg_list is equal to arg_val, and a count of the number of times that arg_val appears in arg_list.

In [5]:
def locate(arg_list, arg_val):
    
    count = 0
    indices = []
    
    for i in range(0, len(arg_list)):
        if arg_list[i] == arg_val:
            indices.append(i)
            count += 1
        
    return indices, count 
In [6]:
grades = ['A', 'D', 'A', 'C', 'B', 'F', 'A', 'D', 'C', 'B', 'F', 'A', 'C', 'B', 'A', 'B', 'B', 'C', 'B', 'F', 'D', 'D', 'A', 'C', 'B']

for letter in ['A', 'B', 'C', 'D', 'F']:
    idx, c = locate(grades, letter)
    print(str(letter) + ': indices = ' + str(idx) + ', count = ' + str(c) )
A: indices = [0, 2, 6, 11, 14, 22], count = 6
B: indices = [4, 9, 13, 15, 16, 18, 24], count = 7
C: indices = [3, 8, 12, 17, 23], count = 5
D: indices = [1, 7, 20, 21], count = 4
F: indices = [5, 10, 19], count = 3

Accessing Global Variables Within Functions

Any variable that is defined outside of a function is called a global variable and is said to exist within the global scope. Such variables are accessible from within Python functions.

In [7]:
def squareA():
    return a**2

def squareB():
    return b**2

a = 37
In [8]:
print(squareA())
1369
In [9]:
#print(squareB())

Although functions can access variables defined within the global scope, they are not generally allowed to alter global variables.

In [10]:
def setAto50():
    a = 50
    return a

a = 37
print(a)
print(setAto50())
print(a)
37
50
37

We can provide a function with permission to alter global variables by including within the function a line consisting of the global keyword followed by the name of a global variable we wish to alter.

In [11]:
def setAto50():
    global a 
    a = 50
    return a

a = 37
print(a)
print(setAto50())
print(a)
37
50
50

Although there are occasions when it is helpful to have a function access or alter a global variable, it is generally bad practice and can result in confusing code or lead to unexpected results. As a rule of thumb, if a function needs to have access to a certain variable in order to perform its task, you should pass that variable to the function as an argument.

In [12]:
def multiply_ab():      # This approach is discouraged.
    return a*b

def multiply(p, q):     # This approach is preferred. 
    return p*q

a = 5
b = 7

print(multiply_ab())
print(multiply(a,b))
    
35
35