Space Python Loading Python…

Unit converter

Write the codeMedium 2 stages

Partner agencies send numbers in their own units: miles, pounds, psi, Fahrenheit. In 1999 a mix-up between pound-force seconds and newton-seconds cost NASA the Mars Climate Orbiter. The team wants one converter that everyone uses, driven by one table, and that refuses loudly when it doesn't know a unit.

Build it, then teach it temperatures.

Write convert(value, from_unit, to_unit). For a pair in CONVERSIONS, multiply by its factor; for the pair the other way round, divide; for the same unit twice, return the value. Raise ValueError for a unit the table doesn't know, unknown unit: ..., or for two known units with no factor between them. Then run the requests:

400 km = 248.55 mi
12.5 lb = 5.67 kg
7.8 km/h = 2.17 m/s
101.3 kPa = 14.69 psi
REFUSED 3 km/s -> km/h: unknown unit: km/s
REFUSED 5 kg -> kPa: no conversion from kg to kPa
42 N = 42.00 N

UNITS, every unit that appears in the table, is built for you at the top. Check both units against it first.

Seven requests
convert() for any pair

Finish stage 1 to unlock this stage.

Temperatures need more than a factor: Fahrenheit is Celsius times 1.8, plus 32. The table now holds (factor, offset) for every pair. Convert with value * factor + offset, and the other way round with (value - offset) / factor:

400 km = 248.55 mi
12.5 lb = 5.67 kg
-60 C = 213.15 K
77 K = -196.15 C
-40 F = -40.00 C
REFUSED 300 K -> F: no conversion from K to F
21 C = 21.00 C

The rest of convert() stays as it was. Kelvin to Fahrenheit has no pair in the table, so it is refused.

Temperatures and the rest
Offsets both ways
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

Creating Dictionaries

creating-dictionaries-python.py
# A dictionary stores pairs: a key, then its value
webb = {
    "name": "James Webb Space Telescope",
    "mirror_metres": 6.5,
    "launched": 2021,
    "instruments": 4,
    "infrared": True,
}
print(webb)

# Square brackets look up a value by its key
print("Mirror width:", webb["mirror_metres"], "metres")

# get() returns a fallback instead of crashing on a missing key
print("Cost:", webb.get("cost", "not recorded"))

# The dict() function builds the same thing from keyword arguments
hubble = dict(name="Hubble", mirror_metres=2.4, launched=1990)
print("Hubble mirror:", hubble["mirror_metres"], "metres")

# Keys do not have to be text. Anything unchangeable works
launch_log = {
    1990: "Hubble",
    2021: "Webb",
    (2027, "planned"): "Roman",
}
print(launch_log[1990])
print("Missions logged:", len(launch_log))
print("Anything launched in 2021?", 2021 in launch_log)
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:].