
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):
crewsmust be greater than0, message must mentioncrews.totalmust not be negative, message must mentiontotal.
The return line is already correct.
Add two sanity checks to the top of split_fuel(total, crews):
crewsmust be greater than0, message must mentioncrews.totalmust not be negative, message must mentiontotal.
The return line is already correct.
main.py Python sleeping
Press Run to try your code, then Check to test it.