Challenge - 5 Problems
Assert Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of assert with a failing condition
What will be the output when running this code?
Python
def check_positive(x): assert x > 0, "Value must be positive" return x print(check_positive(-5))
Attempts:
2 left
💡 Hint
Remember what assert does when the condition is false.
✗ Incorrect
The assert statement checks if the condition is true. If false, it raises an AssertionError with the given message.
❓ Predict Output
intermediate2:00remaining
Assert statement with no message
What is the output of this code snippet?
Python
def test_value(val): assert val == 10 return "Passed" print(test_value(5))
Attempts:
2 left
💡 Hint
What happens if assert condition is false and no message is given?
✗ Incorrect
Assert raises AssertionError without a message if the condition is false.
❓ Predict Output
advanced2:00remaining
Effect of disabling assert statements
What will be the output of this code when run with python -O (optimize) flag?
Python
def check(): assert false, "Fail" return "Checked" print(check())
Attempts:
2 left
💡 Hint
The -O flag disables assert statements.
✗ Incorrect
When Python runs with -O, assert statements are ignored, so the function returns "Checked".
🧠 Conceptual
advanced2:00remaining
Purpose of assert statements in code
Which of the following best describes the main purpose of assert statements in Python?
Attempts:
2 left
💡 Hint
Think about when and why developers use assert.
✗ Incorrect
Assert statements are used to verify assumptions during development and testing, helping catch bugs early.
❓ Predict Output
expert2:00remaining
Output with assert inside a loop and else clause
What is the output of this code?
Python
for i in range(3): assert i < 2, f"Index {i} too high" else: print("Loop completed")
Attempts:
2 left
💡 Hint
Check when the assert fails and if the else block runs.
✗ Incorrect
The assert fails when i is 2, raising AssertionError before the else block can run.