Practice: Assertions

« Read the chapter

Q1. Assert a positive number

BeginnerCoding

Write a program that sets n = 5, asserts that n is greater than 0, and prints ok.

Goal: Write a basic assert statement.

Q2. Assert with a message

BeginnerCoding

Write a function check_age(age) that asserts age >= 0 with the message "age must not be negative" and returns age. Call it with 21 and print the result.

Goal: Add a message to an assertion.

Q3. Catch a failed assertion

BeginnerCoding

Write code that asserts 2 + 2 == 5 inside try/except and prints failed when AssertionError is caught.

Goal: Catch AssertionError.

Q4. Print the assertion message

IntermediateCoding

Write code that triggers assert False, "boom" inside try/except and prints the message stored in the exception.

Goal: Read the message of AssertionError.

Q5. Postcondition on a sort

IntermediateCoding

Write a function sort_checked(items) that returns sorted(items) but asserts that the result has the same length as the input. Print sort_checked([3, 1, 2]).

Goal: Use a postcondition.

Q6. Safe float comparison

IntermediateCoding

Use math.isclose to assert that 0.1 + 0.2 is close to 0.3, then print equal enough.

Goal: Compare floats in assertions.

Q7. Silent pass

BeginnerOutput

What does this program print?

Code
x = 3
assert x == 3
print("done")

Goal: Predict the result of a true assertion.

Q8. Failing assert caught

BeginnerOutput

What does this program print?

Code
try:
    assert 1 > 2, "bad math"
except AssertionError as e:
    print("Error:", e)

Goal: Predict output of a failed assert.

Q9. Not an empty list

IntermediateOutput

What does this program print?

Code
items = []
try:
    assert items, "list is empty"
except AssertionError as e:
    print(e)

Goal: Understand truthiness in asserts.

Q10. Tuple trap

AdvancedOutput

What does this program print? (Python may show a SyntaxWarning on stderr, which is not part of the output.)

Code
assert (1 == 2, "never fails")
print("still running")

Goal: Recognise the tuple trap.

Q11. Lazy message

AdvancedOutput

What does this program print?

Code
def msg():
    print("building message")
    return "oops"

assert True, msg()
print("end")

Goal: Know the message is lazy.

Q12. Two checks in a row

IntermediateOutput

What does this program print?

Code
values = [4, 8, 12]
assert all(v % 4 == 0 for v in values)
assert max(values) == 12
print(sum(values))

Goal: Use all() inside an assert.

Q13. Fix the tuple assert

IntermediateDebugging

The code below never fails even when score is negative. Fix it so the assertion works.

Code
score = -5
assert (score >= 0, "score must be non-negative")
print(score)

Goal: Fix a wrong assert.

Q14. Fix the side effect

AdvancedDebugging

This code removes an item inside an assert, so it behaves differently with python -O. Rewrite it so the pop always happens.

Code
stack = [1, 2, 3]
assert stack.pop() == 3
print(stack)

Goal: Avoid side effects in assert.

Q15. Fix input validation

IntermediateDebugging

This function uses assert to check user input. Change it to raise ValueError when the name is empty. Call it with "Asha" and print the result.

Code
def greet(name):
    assert name != ""
    return "Hello " + name

print(greet(""))

Goal: Choose exceptions for input checks.

Q16. Assert or exception?

IntermediateConceptual

A function receives a number typed by a user in a form. Should you check it is positive with assert or with raise ValueError? Explain.

Goal: Choose between assert and raise.

Q17. What does -O do?

IntermediateConceptual

Explain what happens to assert statements when you run python -O script.py.

Goal: Know the effect of the -O flag.

Q18. Why add a message?

BeginnerConceptual

Give one reason to write a message in an assert statement.

Goal: Explain good messages.

Q19. Invariant in a loop

AdvancedApplication

Write a program that sums the numbers 1 to 5 in a loop, asserting inside the loop that total never decreases. Print the final total.

Goal: Use an invariant.

Q20. Test a function

IntermediateApplication

Write a function square(n), then use three assert statements to test square(2) == 4, square(-3) == 9 and square(0) == 0. Print all good at the end.

Goal: Write simple tests with assert.