Recall & Review
beginner
What is the purpose of the
assert statement in Python?The
assert statement checks if a condition is true. If it is false, it stops the program and raises an AssertionError. It helps catch bugs early by verifying assumptions.Click to reveal answer
beginner
How do you write an
assert statement with a custom error message?Use
assert condition, 'error message'. If the condition is false, Python shows the message with the AssertionError.Click to reveal answer
beginner
What happens when an
assert statement fails?Python raises an
AssertionError and stops running the program unless the error is caught by a try-except block.Click to reveal answer
intermediate
Can
assert statements be disabled? If yes, how?Yes, running Python with the
-O (optimize) flag disables assert statements, so they do not run and do not check conditions.Click to reveal answer
intermediate
Is it good practice to use
assert for data validation in production code?No,
assert is mainly for debugging and testing. For production, use proper error handling because assert can be disabled.Click to reveal answer
What does this code do? <br>
assert 5 > 3
✗ Incorrect
The assert checks if 5 > 3, which is true, so the program continues without error.
What error is raised when an assert condition fails?
✗ Incorrect
When an assert condition is false, Python raises an AssertionError.
How can you disable assert statements in Python?
✗ Incorrect
Running Python with the -O (optimize) flag disables assert statements.
Which is the correct way to add a message to an assert?
✗ Incorrect
The syntax is assert condition, 'message' to show a custom error message.
Should assert be used for checking user input in production?
✗ Incorrect
Assert is for debugging, not for production input validation.
Explain how the assert statement works and when it should be used.
Think about how assert helps catch mistakes early.
You got /4 concepts.
Describe how to write an assert statement with a custom error message and why that might be helpful.
Custom messages make errors clearer.
You got /3 concepts.