PY-101 ยท Testing and debugging
assert
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
assert condition, "message" checks that a condition is True and raises AssertionError with your message if it is False. It is a quick way to state an assumption in code, and it is the core of how tests check results. Do not use it to validate user input, because asserts can be switched off.
- Write assert with a message
- Read an AssertionError
- Know when not to use assert
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
def final_price(price, discount):result = price - discountassert result >= 0, f"price went negative: {result}"return resultprint(final_price(500, 50))try:final_price(100, 150)except AssertionError as e:print("Caught:", e)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
450
Caught: price went negative: -50 ๐ฏ Add three asserts that check to_minutes: to_minutes(1, 30) == 90, to_minutes(0, 5) == 5 and to_minutes(2, 0) == 120. Then fix to_minutes so they pass and print "All good".
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
return hours * 60 + minutes, and write assert to_minutes(1, 30) == 90 etc.
- The problemYour discount function should never return a negative price. One assert line makes the code shout immediately if that assumption is ever broken.
- The Python idea
assert condition, "message if it fails"assert condition, "message" checks that a condition is True and raises AssertionError with your message if it is False. - In real lifeData pipelines assert that row counts match between steps, so a silent data loss stops the job instead of producing a wrong report.
Start with a question
Your discount function should never return a negative price. One assert line makes the code shout immediately if that assumption is ever broken.
Tests are mostly asserts. Writing them is how you prove code works and keep it working.
Explain it like I'm 10
assert is saying "I promise this is true" out loud. If it is not, an alarm goes off with your note attached.
The technical explanation
assert total >= 0, "total must not be negative" does nothing when True.
When False it raises AssertionError: total must not be negative.
pytest turns plain asserts into detailed reports showing the values involved.
Syntax
assert condition, "message if it fails" Real-world scenario
Data pipelines assert that row counts match between steps, so a silent data loss stops the job instead of producing a wrong report.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: pytest basics โQuestions people ask
When should I use assert in Python?
To state internal assumptions that should never be false if your code is correct, and in tests. Not for user input or anything that must always be checked.
Why does my assert with brackets always pass?
assert (x == 1, "msg") asserts a non-empty tuple, which is always True. Write assert x == 1, "msg" without brackets.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner When should I use assert in Python?
To state internal assumptions that should never be false if your code is correct, and in tests. Not for user input or anything that must always be checked.
beginner Why does my assert with brackets always pass?
assert (x == 1, "msg") asserts a non-empty tuple, which is always True. Write assert x == 1, "msg" without brackets.
intermediate What happens when an assert condition is True?
Nothing. Nothing happens; execution continues.
intermediate Which error does a failing assert raise?
AssertionError. AssertionError.
Quick revision
Remember
- Write assert with a message
- Read an AssertionError
- Know when not to use assert
- Running Python with -O turns asserts off. Use if ... raise ValueError(...) for checks that must always happen, like user input.
Syntax
assert condition, "message if it fails" Official documentation
- The assert statement (docs.python.org)