Hone

Lessons · Python · assert

assert says what must be true

assert claim, message does nothing when the claim holds and raises AssertionError with the message when it does not. It is a sentence about your code that the computer checks.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every challenge on Hone is graded by asserts like these. Knowing what one says, and what its silence means, is how you read a failing test instead of fearing it.

How to think about it

Write the claim as you would say it: 'the total is 7', 'the list is not empty'. Put the expected value on the right. Give a message that says what was expected, so the failure reads like a sentence.

Worked example

def add(a, b):
    return a + b
assert add(2, 3) == 5
Holds: nothing happens.
try:
    assert add(2, 2) == 5, 'expected 5'
Does not hold: raises, with the message.
except AssertionError as e:
    print('failed:', e)
failed: expected 5
print('done')
done

Your turn

Claim that the list came back empty.

assert result == , 'expected no items'

The trap

assert some_list to mean 'the list exists'. It means 'the list is truthy', so an empty list fails the claim.

Practise assert on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.