We know this routine will always fail with negative numbers so we can detect this precondition early on and raise an exception at that point, a technique called a guard clause:
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. Raises: ValueError: If x is negative. """ if x < 0: raise ValueError("Cannot compute square root of negative number{}".format(x)) guess = x i = 0 while guess * guess != x and i < 20: guess = (guess + x / guess) / 2.0 i += 1 return guess
The test is a simple if
-statement and a call to raise passing a newly minted exception
object. The ValueError()
constructor accepts an error message. See how we also modify the docstring to make it plain which exception type will be raised by sqrt()
and under what circumstances...