Any number of values
Engineers check averages all day: three spot readings typed by hand, a whole pass from the database, sometimes just two numbers. A function that wants a list makes every one of those calls a little clumsier than it needs to be.
Write an average that takes the values as they come, then give it a rounding option.
Finish stage 1 to unlock this stage.
Write average(*values), which takes any number of numbers and returns their mean. Call it with three loose values, then with the readings list unpacked, and print:
Three spot checks: 401.0 The whole pass: 419.5
Inside the function, values is a tuple, so sum() and len() work on it. In the second call, average(*readings) passes the five readings as five separate arguments.
Finish stage 1 to unlock this stage.
Add a rounding option, decimals=1, after *values, and return None when there are no values at all. Round the whole pass to two places and add a call with nothing in it:
Three spot checks: 401.0 The whole pass: 419.5 No values: None
Because it comes after *values, decimals can only be passed by name: average(*readings, decimals=2).
Hints
Variable Number of Arguments *args
# The star collects every extra positional argument into a tuple
def stack_frames(target, *frames):
print(target, "->", len(frames), "frames")
print("Collected as:", frames)
total = 0
for seconds in frames:
total = total + seconds
print("Total exposure:", total, "seconds")
print()
# Three extra values
stack_frames("Crab Nebula", 30, 30, 45)
# Five extra values, same function, nothing changed
stack_frames("Sombrero Galaxy", 60, 60, 90, 120, 120)
# None at all, and frames is simply an empty tuple
stack_frames("Lagoon Nebula")
# The name args is only a convention. The star is what does the work
def log_all(*anything):
print(anything)
log_all("Deneb", 5, True)
# A star at the call site does the opposite: it spreads a list back out
session = [90, 90, 180]
stack_frames("Whirlpool Galaxy", *session)
Separate arguments with commas. They're passed on every Run as sys.argv[1:].