What does the assert statement do, and when should you not use it?
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
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 emptyRunning 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.