Assert — Python Technical Interview Questions & Answers
Assert
Assert
- assert condition, "msg" checks a belief while developing. If False, AssertionError. Good for internal checks, not for user input validation in production (can be disabled with python -O).
- Example: assert marks >= 0. If marks is -5, the script stops with a clear message.
- Output: ok 72. If marks were -5, AssertionError. python -O can skip asserts.
Technical Interview Tip: What assert does + python -O warning.
Code Examples for Assert
Example
# Assert
marks = 72
assert marks >= 0, "marks cannot be negative"
print("ok", marks)
Output: ok 72. If marks were -5, AssertionError. python -O can skip asserts.
How to Explain Assert to an Interviewer
Explain Assert as if you are teaching a junior — definition, then one tiny script.
assert checks a condition. False → AssertionError.
What does the example print, and why?
ok 72
What mistake do freshers make with Assert?
False → AssertionError.