Extract a function
The navigation display shows how far the ship is from each waypoint. The distance formula was written once and then pasted for the next two waypoints, with the variable names changed by hand. One wrong name in one copy and the display would lie about one waypoint only.
Give the formula a name, call it three times, then let it help choose where to go next.
Finish stage 1 to unlock this stage.
Move the distance calculation into a function distance_km(a, b) that returns the distance between two (x, y, z) points, and use it for all three waypoints. The output must stay exactly the same:
To waypoint A: 193.0 km To waypoint B: 323.3 km To waypoint C: 7.7 km
Inside the function, use a and b instead of ship and a waypoint. The rounding stays in the prints.
Finish stage 1 to unlock this stage.
Put the waypoints in a dict, waypoints = {"A": waypoint_a, "B": waypoint_b, "C": waypoint_c}, loop over it to print each distance, and print the nearest one at the end:
To waypoint A: 193.0 km To waypoint B: 323.3 km To waypoint C: 7.7 km Nearest: C (7.7 km)
Call distance_km() once per waypoint, and remember the smallest distance seen so far and its name.
Hints
Creating Simple Functions
# Functions in Python
# A function is a reusable block of code
def mission_greeting():
print("Welcome aboard the ISS")
print("All systems nominal")
mission_greeting()
# Functions with a parameter
def check_oxygen(level):
print(f"Oxygen level: {level}%")
if level < 20:
print("ALERT: Oxygen critically low")
check_oxygen(95)
check_oxygen(12)
# Functions that return a value
def earth_weight_to_moon(earth_kg):
moon_gravity = 0.166
return earth_kg * moon_gravity
astronaut_weight = earth_weight_to_moon(82)
print(f"Weight on Moon: {astronaut_weight:.1f} kg")
backpack_weight = earth_weight_to_moon(45)
print(f"Backpack on Moon: {backpack_weight:.1f} kg")
# Functions with multiple parameters
def travel_time(distance_km, speed_kph):
hours = distance_km / speed_kph
return hours
# Earth to Moon
moon_hours = travel_time(384400, 40000)
print(f"\nMoon trip: {moon_hours:.1f} hours")
# Earth to Mars
mars_hours = travel_time(225_000_000, 58000)
mars_days = mars_hours / 24
print(f"Mars trip: {mars_days:.0f} days")
# Try it yourself
# What does earth_weight_to_moon(0) return?
# Calculate travel time to Jupiter: 778_500_000 km
Separate arguments with commas. They're passed on every Run as sys.argv[1:].