Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What does the assert statement do, and when should you not use it?

SHORT ANSWER

assert condition, message raises AssertionError if the condition is false. It is for internal sanity checks during development. Do not use it to validate user input, because assertions are removed when Python runs with the -O flag.

Explain it simply

An assert is a self-check that a developer leaves in the code, like a teacher's note "the total must be 100 here". If the note is wrong, the program stops loudly. It is a statement about what you believe must be true, not a way of handling bad data from outside.

Example

python
def average(marks):
    assert len(marks) > 0, "marks list must not be empty"
    return sum(marks) / len(marks)

print(average([60, 80]))     # Output: 70.0

try:
    average([])
except AssertionError as e:
    print(e)                 # Output: marks list must not be empty

Running python -O script.py strips every assert, so in that mode average([]) would instead fail with ZeroDivisionError. Validation that must always run needs an explicit if and a real exception such as ValueError.

What to say in the interview

"assert is a debugging aid for conditions that should never be false. It raises AssertionError and can be disabled with python -O, so I never use it for input validation or security checks. For those, I raise ValueError or a custom exception. In tests, plain assert statements are the standard in pytest."

Common mistakes

  • Writing assert (cond, "message") with parentheses. A non-empty tuple is always true, so the assertion never fires.

#python#exceptions#debugging

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.