This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Testing with assert, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What happens when an assert condition is false?
Answer: AssertionError is raised
Why: A failed assert raises AssertionError.
What is the part after the comma in assert x == 3, 'x should be 3'?
Answer: A message attached to the failure
Why: The second expression becomes the AssertionError message.
What does running Python with -O do to assert statements?
Answer: Removes them
Why: The -O flag strips assert statements, so do not use them for security checks.
Where is assert appropriate?
Answer: In tests and internal invariants
Why: Assert documents assumptions; it is not a user-input validation mechanism.
Complete the statement that checks the sum.
total = 2 + 2
____ total == 4
print("ok")Answer: assert
Why: The keyword assert begins the check.
Complete the expected value in the message.
total = 2 + 2
assert total == 4, "total should be ____"Answer: 6
Why: The message should state the expected total.
Complete the exception type.
try:
assert False
except ____ as error:
print("caught")Answer: AssertionError
Why: A failed assert raises AssertionError.
Complete the expected square.
def square(n):
return n * n
assert square(3) == ____
print("ok")Answer: 9
Why: Three squared is nine.
What is printed?
assert 2 + 2 == 4
print("ok")Answer: ok
Why: The assertion passes, so the next line runs.
What is the output?
def f(n):
return n * 2
assert f(3) == 6
print(f(3))Answer: 6
Why: The function returns six, and the assertion passes.
What does this code print?
try:
assert False, "bad"
except AssertionError as error:
print(error)Answer: bad
Why: The message after the comma becomes the exception text.
What does the program output?
assert isinstance("x", str)
print("str")Answer: str
Why: The string passes the isinstance check, so str is printed.
Try the questions first
Open the practice page for Python Testing with assert and answer the same 12 questions with instant feedback.