Lesson 59 of 60
โฎPrev Nextโฏ

PY-101 ยท Testing and debugging

assert

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

59of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    assert, running
    1. def final_price(price, discount):
    2. result = price - discount
    3. assert result >= 0, f"price went negative: {result}"
    4. return result
    5. print(final_price(500, 50))
    6. try:
    7. final_price(100, 150)
    8. except AssertionError as e:
    9. print("Caught:", e)
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemYour discount function should never return a negative price. One assert line makes the code shout immediately if that assumption is ever broken.
    2. The Python ideaassert condition, "message if it fails"assert condition, "message" checks that a condition is True and raises AssertionError with your message if it is False.
    3. 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"

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    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.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What happens when an assert condition is True?
    2. 2. Which error does a failing assert raise?
    3. 3. Should you validate user input with assert?
    4. 4. assert 2 + 2 == 5, "maths" raises?
    5. 5. Where are asserts used most?

    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