Exceptions are an important aspect of the API of a function. Callers of a function need to know which exceptions to expect under various conditions so that they can ensure appropriate exception handlers are in place. We'll use square-root finding as an example, using a home-grown square-root function, courtesy of Heron of Alexandria (although he probably didn't use Python).
Callers of a function need to know which exceptions to expect:
Place the following code in a file roots.py:
def sqrt(x):
"""Compute square roots using the method of Heron of Alexandria.
Args:
x: The number for which the square root is to be computed.
Returns:
The square root of x.
"""
guess = x
i = 0
while guess * guess != x and i < 20:
guess = (guess + x / guess) / 2.0
i += 1
return guess
def main():
print(sqrt(9))
print(sqrt(2))
if __name__ == '__main__':
main()
There's only one language feature in this program we haven't met before: The logical and operator which we use in this case to test that two conditions are True on each iteration of the loop. Python also includes a logical or operator which can be used to test whether either or both of its operands are True.
Running our program, we can see that Heron was really on to something:
$ python3 roots.py
3.0
1.41421356237