Assertions

Assertions help to debug and test your code. See exceptions.


In [ ]:
def divide(a, b):
    assert(b!=0), 'The numerator is 0!'
    return a//b

divide(1, 0)

In [ ]:
try:
    divide(1, 0)
except Exception as e:
    print(e)

Assertions are ignored when the interpreter runs in release (optimized) mode:


In [ ]:
!python -c "assert(False); print('In debug mode this is not printed')"

In [ ]:
!python -O -c "assert(False); print('You are running in optimized mode')"