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.
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)
� 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.
def num_divisions(num, div):
temp = num
count = 0
while(temp % div == 0):
temp = temp / div
count += 1
return count, temp
count, rem = num_divisions(900, 2)
print('Count:', count)
print('Remainder:', rem)
count, rem = num_divisions(6237, 3)
print('Count:', count)
print('Remainder:', rem)
� 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
.
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
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) )
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.
def squareA():
return a**2
def squareB():
return b**2
a = 37
print(squareA())
#print(squareB())
Although functions can access variables defined within the global scope, they are not generally allowed to alter global variables.
def setAto50():
a = 50
return a
a = 37
print(a)
print(setAto50())
print(a)
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.
def setAto50():
global a
a = 50
return a
a = 37
print(a)
print(setAto50())
print(a)
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.
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))