Returning Multiple Values¶
It is possible for a Python function to return multiple values. To To accomplish this, we can combine the desired return values together into a list or a tuple, which we then return. Alternately, we can simply list the return values in the return statement, separated by commas.
When storing the values returned by such a function in variables, we can list the target variable names on the left of the assignment operator, 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)
32
25
Example: Division with Remainder¶
Write a function div_w_remainder()
that takes two arguments, num
and div
, and returns the number of times that div
evenly divides num
(i.e. the quotient), as well as the remainder of num
after division by div
. Coerce the remainder into an integer.
def div_w_remainder(num, div):
quotient = int(num/div)
remainder = num % div
return (quotient, remainder)
We will now consider several examples to test our function.
q, r = div_w_remainder(17, 3)
print('Quotient: ', q)
print('Remainder:', r)
Quotient: 5
Remainder: 2
q, r = div_w_remainder(459, 17)
print('Quotient: ', q)
print('Remainder:', r)
Quotient: 27
Remainder: 0
q, r = div_w_remainder(6237, 13)
print('Quotient: ', q)
print('Remainder:', r)
Quotient: 479
Remainder: 10
Example: Locating Elements in a List¶
Write a function called locate
. The function should take two arguments: a list called x
, and another variable called item
.
The function should return two values: A list of indices at which the element in x
is equal to item
, and a count of the number of times that item
appears in x
.
def locate(x, item):
index_list = []
for i in range(0, len(x)):
if x[i] == item:
index_list.append(i)
return (index_list, len(index_list))
A list of student grades is provided in the cell below. Call locate()
five times. In each function call, pass in grades
for x
. For item
, use each of the following values: 'A'
, 'B'
, 'C'
, 'D'
, and 'F'
.
For each function call, print out a message of the following form:
A: 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) )
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