Introduction
Assertions¶
Assertions are a way to stop code and defensively code to make sure that conditions are being met. The format is:
assert bool
This will stop the program if it is false, but nothing happens if it is true.
In [1]:
#If the assertion is true then nothing happens
assert 5==5
print("Good to go")
In [2]:
#But if it is false we stop the program
assert 5==6
print("Good to go")
We can see above that the code stopped when we had false. If you want an actual message to be printed with the assertion if it happens then you can with the following format:
assert bool, error_message
In [3]:
#You can also give an error message
assert 5==6, "Numbers not equal"
print("Good to go")
A classic thing to check is to make sure that you have the correct type when using a variable. For example, checking to make sure we have an integer.
In [4]:
#You might use this to check the type of a variable, for example
assert type(5)==int, "This is not an integer"
print("Good to go")
In [5]:
assert type('5')==int, "This is not an integer"
print("Good to go")
This is good in the context of a function to make sure you have the correct arguments.
In [6]:
#We would use this for functions to ensure we have the correct arguments
def add(a, b):
assert type(a)==int and type(b)==int,"Arguments must be integers"
return a+b
c = add(1,4)
print(c)
In [7]:
c = add('1',4)
print(c)