Paul's Python CoursePPC

assert

Not met yet

assert condition does nothing when the condition is true, and stops the program with an AssertionError when it's false. assert x == y, "message" adds a message; the part after the comma is never compared with anything. In a test, the expected answer must come from somewhere other than the code being tested.

Try it

main.py
def to_minutes(time):
    hours, mins = time.split(":")
    return int(hours) * 60 + int(mins)

assert to_minutes("06:42") == 402
print("checked")

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks a failed assert prints a warning and the program carries on.
  • Thinks assert prints True or False.
  • Thinks assert a, b checks that a equals b, when b is only the message.
  • Thinks a test's expected answer can come from calling the code being tested.

Where it comes up