Space Python Loading Python…

Any number of values

Write the codeEasy 2 stages

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.

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.

Two kinds of call
Any number of values

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).

Round and handle nothing
decimals only by name
You're not logged in, so your progress is kept in this browser only. Log in to save it, and to use hints and solutions.

Hints

Variable Number of Arguments *args

variable-arguments-args.py
# 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)
Open the full example
script.py
PythonLn 1, Col 1Spaces: 4
Loading the Python environment…

Separate arguments with commas. They're passed on every Run as sys.argv[1:].