A Python function always
return
s
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.
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
int
s
or
float
s.
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
tuple
.
t = stats(listOfInts) #t is a tuple. print(f"minimum = {t[0]}") print(f"maximum = {t[1]}") print(f"average = {t[2]}")
statistics.mean
.
What would
statistics.mean
do if the
collection
had no numbers?
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 = 26If we pass the argument
10
to
stats
,
<class 'TypeError'> 'int' object is not iterableIf we pass the empty list
[]
to
stats
,
<class 'ValueError'> min() arg is an empty sequenceIf we pass the empty list
["hello"]
to
stats
,
<class 'TypeError'> can't convert type 'str' to numerator/denominator