Space Python Loading Python…

Guard clauses

Fix the codeMedium 2 stages

The docking computer decides whether the ship may dock. Its function has grown one condition at a time, each inside the last, and the reason for a refusal now sits four levels deep, at the far end of an else whose if is off the top of the screen.

Flatten the function without changing a single answer, then add the next rule the docking team has asked for.

Rewrite can_dock() as guard clauses: check each reason to refuse on its own, return the reason straight away, and return the approval at the end. Every answer must stay the same:

Docking approved
Too fast
Angle too steep
Crew not ready
Port occupied

Keep the order of the checks: port, crew, speed, angle. Flip each condition, for example if not port_free:, and no else is needed.

Same answers
Flat checks

Finish stage 1 to unlock this stage.

The docking team adds a rule: the docking lights must be on. Add a parameter lights_on with a default of True, so the existing calls keep working, and a guard after the crew check. A sixth call tests it:

Docking approved
Too fast
Angle too steep
Crew not ready
Port occupied
Docking lights off

Add the call at the bottom: print(can_dock(0.05, 1.0, True, True, lights_on=False)).

Add the rule
Still flat
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

Early Exit from Function

early-exit-from-function.py
# Check the deal breakers first and leave the moment one fails
def launch_check(wind_kph, fuel_pct, crew_ready):
    if wind_kph > 40:
        return "HOLD: wind too strong"
    if fuel_pct < 95:
        return "HOLD: fuel low"
    if not crew_ready:
        return "HOLD: crew not ready"
    return "GO for launch"

print(launch_check(18, 99, True))
print(launch_check(52, 99, True))
print(launch_check(18, 80, False))

# A bare return simply stops the function and hands back None
def log_anomaly(code):
    if code == 0:
        return
    print("Anomaly", code, "logged")

log_anomaly(0)
log_anomaly(7)

# Inside a loop, return leaves the loop and the function together
def first_clear_window(forecasts):
    for day, clouds in forecasts:
        print("checking", day)
        if clouds < 20:
            return day
    return "no window this week"

week = [("Mon", 80), ("Tue", 45), ("Wed", 10), ("Thu", 5)]
print("Launch on:", first_clear_window(week))
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:].