Space Python Loading Python…

Validate a cargo record

Write the codeMedium 2 stages

Cargo records arrive from several warehouses, typed by different people. Before an item goes on the manifest, it has to pass a check, and when it fails, the warehouse needs to know everything that is wrong with it, not just the first problem.

Write the check as a function that collects the problems, then add a rule for the ID format.

Write validate_cargo(item), which returns a list of problems: one missing ... for each field in REQUIRED that the record doesn't have, in that order, and negative mass for a mass below 0. The loop at the bottom then prints:

CG-0042: OK
CG-0043: missing item, negative mass
CG-0044: missing mass_kg
CG-42: OK

Start with problems = [], append each problem you find, and return problems at the end. Check that "mass_kg" is there before comparing it.

Check the records
A list of problems for any record

Finish stage 1 to unlock this stage.

Cargo IDs have a fixed format: CG- followed by exactly four digits. Add bad ID format to the problems when the ID doesn't match:

CG-0042: OK
CG-0043: missing item, negative mass
CG-0044: missing mass_kg
CG-42: bad ID format

Check that the ID starts with "CG-", is 7 characters long, and that item["id"][3:].isdigit(). Only check an ID that is there.

Check the ID format
Right for any ID
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:].