#!/usr/bin/env python # coding: utf-8 # (Assert)= # # Assert # ``` {index} Assert (Python) # ``` # # Assert statement allows us to do sanity checks in our code. It is also a very handy tool in preventing bugs that do not throw an `Error`. Consider the following factorial function: # # In[10]: def fact(n): result = 1 for i in range(n): result*=i return result fact(-1) # What if $n = 1.5$, $n = -1$ or $n $ is not a numeric type? Our function is defined for non-negative integers only. However, for some of those invalid inputs, the function can actually return something! `assert` is a great feature to add here: # In[9]: def fact(n): assert n is int and n >=0 result = 1 for i in range(n): result*=i return result fact(-1) # Now our program throws an `AssertionError` and we immediately know that the input is invalid. While in this simple example such precautions might seem to be an overkill, `assert` scales very well. When multiple functions exchange data, this feature might shorten the debugging time **a lot**. # If you do not want your program to crash because of the `AssertionError` surround your code with the `try..except` block: # In[8]: def fact(n): try: assert n is int and n >=0 result = 1 for i in range(n): result*=i return result except AssertionError: print("This is an invalid input") fact(-1) # In some coding regimes, `assert` is considered acceptable only in the development process. It is often `deactivated` in the final version of the software. # (assert_exercises)= # ## Exercises # # * **Perimeter of a circle** Define a function which calculates the perimeter of a circle given its radius. # # **HINT**: `import math` for the value of $\pi$. Do not assume that `r` is of any particular type. # ````{admonition} Answer # :class: dropdown # # ```python # from math import pi # # def perimeter(r): # assert r >=0 # return 2* math.pi*r # # ``` # # ```` # In[ ]: