Space Python Loading Python…

Summary function

Write the codeMedium 2 stages

In "Readings summary" you printed the min, max and mean of one pass. Now the dashboard, the daily report and the alert system all need those numbers, each in its own format, for every pass, including the ones where the sensor sent nothing.

Write one function that returns the whole summary, then make it safe for an empty pass.

Write summarise(readings), which returns a dict with the keys count, min, max and mean. Then print(summarise(pass_1)) prints:

{'count': 5, 'min': 398.0, 'max': 455.2, 'mean': 419.5}

Build the dict in the return line, with len(), min(), max() and sum() / len().

Summarise a pass
A dict for any readings

Finish stage 1 to unlock this stage.

The second pass had no data, and min([]) stops with a ValueError. For an empty list, return a count of 0 and None for the other three. Round the mean to one decimal place, too. Print both passes:

{'count': 5, 'min': 398.0, 'max': 455.2, 'mean': 419.5}
{'count': 0, 'min': None, 'max': None, 'mean': None}

Check if not readings: first and return early.

Handle an empty pass
Right for any readings
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

Returning Dictionary or List

returning-dictionary-list.py
# Returning complex data structures from functions

def planet_data(name):
    """Returns dictionary with planet info."""
    database = {
        "Mars": {"diameter_km": 6779, "moons": 2, "type": "rocky"},
        "Jupiter": {"diameter_km": 139820, "moons": 95, "type": "gas giant"},
        "Saturn": {"diameter_km": 116460, "moons": 146, "type": "gas giant"}
    }
    return database.get(name, {"error": f"Planet {name} not found"})


def mission_checklist(crew_size, days):
    """Returns list of supply items scaled to crew and duration."""
    water_liters = crew_size * days * 2.5
    food_kg = crew_size * days * 1.8
    oxygen_kg = crew_size * days * 0.84

    return [
        f"Water: {water_liters:.0f} liters",
        f"Food: {food_kg:.0f} kg",
        f"Oxygen: {oxygen_kg:.1f} kg"
    ]


mars = planet_data("Mars")
print(f"Mars has {mars['moons']} moons and is {mars['type']}")

pluto = planet_data("Pluto")
print(pluto)

supplies = mission_checklist(4, 180)
print("Mission supplies needed:")
for item in supplies:
    print(f"  - {item}")
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:].