Intermediate tests: assert statements


In [ ]:
assert True, "This is an assert statement"

In [1]:
num = 2.003

In [2]:
assert num > 2, "Value must be > 2"

In [3]:
assert num < 2.001, "value can only be a bit bigger than 2"


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-3-c87e23167cb5> in <module>()
----> 1 assert num < 2.001, "value can only be a bit bigger than 2"

AssertionError: value can only be a bit bigger than 2

For example, if you write a function and you know which is the field within which it does work, check that the input values are in the defined range.

(e.g. if the temperature is in Kelvin, negative numbers should cause a crash.)


In [8]:
def temp_C_to_K(temp_in_C):
    """Convert temperature from C to K
    """
    
    temp_in_K = temp_in_C + 273.15
    assert temp_in_K > 0, "value in K should be greater than zero"
    return temp_in_K

In [11]:
print temp_C_to_K(-280)


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-11-5e07e1b4c5e4> in <module>()
----> 1 print temp_C_to_K(-280)

<ipython-input-8-fb2f072b0040> in temp_C_to_K(temp_in_C)
      4 
      5     temp_in_K = temp_in_C + 273.15
----> 6     assert temp_in_K > 0, "value in K should be greater than zero"
      7     return temp_in_K

AssertionError: value in K should be greater than zero

In [ ]: