← All lessons

assert: a quick check

Sign in · Sign up

Lesson 8.5

assert checks a condition and stops the program if it is false:

assert len(password) >= 8, "The password is too short"

Condition true — assert does nothing and the code goes on. Condition false — an AssertionError is raised with the message.

Write a function check_password(password) that:

  • raises an AssertionError with the message The password is too short if the password has fewer than 8 characters;
  • otherwise returns the string The password is fine.

Without assert the same result would come from raise, but for checking your own assumptions assert is shorter to write. Check: assert len(password) >= 8, "..." — and then straight to return.

Remember: assert is for checking your own assumptions (in tests, for example). Check user input errors with try/except: the user should never see an AssertionError.

Hint

assert goes on the first line of the function, return on the second.

The condition checks the password length, and after the comma there is a message in quotes — it becomes the text of the error.