Multiple Return Values

Multiple Return Values

A return with several values, separated by commas, returns them as a tuple:

def divide(dividend, divisor):
    return dividend // divisor, dividend % divisor

result = divide(17, 5)
print(result)

Output:

(3, 2)

The caller usually unpacks straight into variables:

quotient, remainder = divide(17, 5)
print(quotient)
print(remainder)

Output:

3
2

Two built-in functions are useful here and from now on: min and max return the smallest and largest element of a list — min([4, 1, 9]) is 1, max([4, 1, 9]) is 9.

Exercise

  1. Define a function named price_range with one parameter, prices (a non-empty list of numbers).
  2. It returns two values: the lowest price and the highest price, in that order.
low, high = price_range([40, 12, 87, 30])

gives low = 12 and high = 87.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestPriceRange(unittest.TestCase):
    def test_four_prices(self):
        self.assertEqual(price_range([40, 12, 87, 30]), (12, 87))

    def test_single_price_is_both_low_and_high(self):
        self.assertEqual(price_range([25]), (25, 25))

    def test_order_is_low_then_high(self):
        low, high = price_range([5, 1, 9])
        self.assertEqual(low, 1)
        self.assertEqual(high, 9)
def price_range(prices):
    return min(prices), max(prices)


low, high = price_range([40, 12, 87, 30])
print(low)
print(high)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.