Returning Several Values
A function returns one value. But that value can be a tuple, and a tuple holds several values. So when a function should give back two results, return them separated by a comma:
def lowest_and_highest(numbers):
return min(numbers), max(numbers)
temperatures = [18, 25, 31, 22, 28]
print(lowest_and_highest(temperatures))(18, 31)return min(numbers), max(numbers) returns the tuple (18, 31): as in the swap, the comma makes a tuple. Where you call the function, unpack the tuple right away into two variables whose names say what they hold:
lowest, highest = lowest_and_highest(temperatures)
print(f"From {lowest} to {highest} degrees")From 18 to 31 degreesA function can return three values or more the same way, and the call then unpacks them into as many names.
Watch the number of names here too. With a single name, result = lowest_and_highest(temperatures), there's no error: result holds the whole tuple. And when the function returns only one value, but the call unpacks it into two names, the program ends with an error:
def lowest_and_highest(numbers):
return min(numbers)
lowest, highest = lowest_and_highest([18, 25, 31])Traceback (most recent call last):
File "<exec>", line 4, in <module>
TypeError: cannot unpack non-iterable int objectThe function returned a single number, 18, and a number can't be split into two values. Non-iterable means that it isn't a collection of values that Python could go through one by one, as it goes through a tuple, a list or a text.
Instructions
- 1
The program ends with
TypeError: cannot unpack non-iterable int object: the call unpacks two values, but the function returns only one, the total. Makeround_stats()return the average too,sum(numbers) / len(numbers), as the second value. The program then printsTotal: 43andAverage: 10.75. Keep the linepoints = [12, 7, 15, 9]: the exercise also tries other points. - 2
Add a third value: the best score of the round,
max(numbers). Return it from the function as well, unpack it into a third variable,best, and printBest: 15at the end.