A function that returns a tuple.

A Python function always returns exactly one return value. For example, if the function does not explicitly return anything, it implicitly returns the value None. If you need to return more than one, the workaround is to create and return a tuple containing more than one item.

returntuple.py

The argument of the function stats must be an iterable (such as a list, tuple, set, frozenset, range, etc.) containing at least one item, and all of the items in the iterable must be ints or floats. The expression
isinstance(item, (int, float))
in line 17 means
isinstance(item, int) or isinstance(item, float)
Lines 17–18 ensure that every item in the collection is a number.

minimum = 10
maximum = 50
average = 26.0

Things to try

  1. Verify that the outer pair of parentheses in line 20 are optional. Their only purpose is to remind us that we’re returning a tuple.
  2. Verify that the parentheses to the left of the equal sign in line 23 are optional.
  3. Verify that you could also write lines 24–28 as follows, although it would be less clear than what we have now.
    t = stats(listOfInts)   #t is a tuple.
    
    print(f"minimum = {t[0]}")
    print(f"maximum = {t[1]}")
    print(f"average = {t[2]}")
    
  4. Instead of computing the average by summing and dividing in line 20, call statistics.mean. What would statistics.mean do if the collection had no numbers?
  5. Instead of terminating the program in the stats function if something goes wrong, we could let an exception escape from stats and then catch the exception down in the code that calls stats. Note that len, min, and max raise ValueError upon division by zero, but statistics.mean raises statistics.StatisticsError upon division by zero.

    import sys
    import statistics
    
    def stats(collection):
        "Return the minimum, maximum, and average of the numbers in a collection."
        #Throw caution to the wind:
        return min(collection), max(collection), statistics.mean(collection)
    
    
    listOfInts = [10, 20, 50, 30, 20]
    
    try:
        minimum, maximum, average = stats(listOfInts)
    except BaseException as error:
        print(error, file = sys.stderr)
        sys.exit(1)
    
    print(f"minimum = {minimum}")
    print(f"maximum = {maximum}")
    print(f"average = {average}")
    sys.exit(0)
    
    minimum = 10
    maximum = 50
    average = 26
    
    If we pass the argument 10 to stats,
    <class 'TypeError'> 'int' object is not iterable
    
    If we pass the empty list [] to stats,
    <class 'ValueError'> min() arg is an empty sequence
    
    If we pass the empty list ["hello"] to stats,
    <class 'TypeError'> can't convert type 'str' to numerator/denominator