Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python assert statements code

Practice writing assertions, attaching diagnostic messages, and choosing explicit exceptions when a check must always run.

Intermediate ~8 min read

Challenge 1

Require that count is positive before returning it.

python Your answer
def positive_count(count):
    
    return count

print(positive_count(3))

Press Ctrl⌘Enter to check your answer

Challenge 2

Add a useful message to this assertion so a failed invariant explains itself.

python Your answer
limit = 5
value = 8

try:
    assert value <= limit, 
except AssertionError as error:
    print(error)

Press Ctrl⌘Enter to check your answer

Challenge 3

Replace the missing code with explicit validation so a negative value always raises ValueError.

python Your answer
def set_level(level):
    if level < 0:
        
    return level

try:
    set_level(-1)
except ValueError as error:
    print(type(error).__name__)

Press Ctrl⌘Enter to check your answer

Challenge 4

Add the assertion that documents the internal invariant before using the first item.

python Your answer
def first(items):
    
    return items[0]

Press Ctrl⌘Enter to check your answer