Docstring and type hints
The flight dynamics team wrote fuel_needed(), and now other teams want to call it. Is the reserve a percentage or a share? Does it work with whole seconds? What comes back? Nobody wants to read the body of every function to find out.
Document the function where Python, editors and other programmers can find it.
Finish stage 1 to unlock this stage.
Add a docstring to fuel_needed(): a string in triple quotes as the first line inside the function, saying what it returns and what the reserve means. The output doesn't change:
Burn 1: 330.0 kg Burn 2: 135.0 kg
For example:
"""Fuel in kg for an engine burn, including a reserve.
The reserve is a share of the burn's own fuel: 0.1 adds 10%.
"""The test reads fuel_needed.__doc__, so the string has to come right after the def line, before the return.
Finish stage 1 to unlock this stage.
Add type hints: each parameter is a float, and so is the return value. Keep the default reserve and the docstring:
def fuel_needed(burn_time_s: float, flow_rate_kg_s: float, reserve: float = 0.1) -> float:
Whole numbers like 120 can still be passed: an int is accepted wherever a float is expected.
Hints
Documenting Functions
# A docstring is a text block placed as the first thing inside a function
def km_to_au(km):
"""Convert a distance in kilometres to astronomical units."""
return km / 149597870.7
# A longer docstring can spell out the inputs and what comes back
def light_minutes(km):
"""Work out how long light takes to cross a distance.
Args:
km: the distance in kilometres
Returns:
The travel time in minutes, as a float.
"""
return km / 299792.458 / 60
# Jupiter sits about 778.5 million kilometres from the Sun
print("Distance in AU:", round(km_to_au(778500000), 2))
print("Light takes:", round(light_minutes(778500000), 1), "minutes")
# Python stores the docstring on the function itself
print(km_to_au.__doc__)
# help() prints the name, the parameters and the docstring together
help(light_minutes)
Separate arguments with commas. They're passed on every Run as sys.argv[1:].