Space Python Loading Python…

Test the alert levels

Write the codeMedium 2 stages

The engine alert check from "Alert level" is now a function, alert_level(), and other programs depend on it. Before anyone changes it again, it needs tests: small checks that run in a second and shout when the function gives a wrong answer.

Write the checks. To see whether they are any good, the hidden tests run them against broken copies of the function, and good checks catch every one.

Below the function, write assert checks: one temperature that should give OK, one for WARN and one for CRITICAL. When they all hold, print:

All checks passed

For example, assert alert_level(20) == "OK". Leave the function exactly as it is: the hidden tests break copies of it and expect your checks to notice.

Checks that pass
Checks that catch mistakes

Finish stage 1 to unlock this stage.

Bugs hide at the boundaries. Add checks for the values exactly on each threshold and just below them: 400 and 450, and 399.9 and 449.9. Keep the passed line at the end.

The hidden tests now break the function the way people really do: > instead of >=, or a threshold off by one.

Checks that pass
Checks that catch boundary mistakes
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:].