Code

Sanity Checks

assert checks that something you believe is true really is true. If it isn't, the program stops immediately with an AssertionError and your message:

def split_gold(gold, people):
    assert people > 0, "people must be at least 1"
    return gold // people

split_gold(10, 0)
# AssertionError: people must be at least 1

That's much clearer than a confusing crash three functions later!

  • Write assert condition, "message".
  • Use it to catch programmer mistakes, "this should never happen".
  • Python can switch asserts off (with python -O), so don't rely on them to check user input. For that you'll learn proper exceptions in the next course.

Assignment

Add two sanity checks to the top of split_fuel(total, crews):

  1. crews must be greater than 0, message must mention crews.
  2. total must not be negative, message must mention total.

The return line is already correct.