# Python 3 # Author: Jonathan Goodman, goodman@cims.nyu.edu # Fall 2024 # for the class Scientific Computing # https://math.nyu.edu/~goodman/teaching/ScientificComputing2024/ScientificComputing.html # Illustrate a function reporting failure and the calling code dealing # with it. # This file: exceptionDemo.py, import numpy as np # return the NaN generated by np.sqrt if x < 0 -- creates a mess def myRootNaN(x): # return NaN if x is negative return np.sqrt(x) # makes NaN if x<0, but also raises an error flag. # Either turn off the error flag or use the ... # ... myRootNone(x) function below. # test for x<0 and return None if it is. Clean result. def myRootNone(x): # Return None if x is negative if x >= 0.: return np.sqrt(x) else: return None # This reports failure # test for x<0 and raise an exception if it is. The official method. class NegativeArgument(Exception): # Create a named excdeption. This ... pass # .. exception class exists but does nothing def myRootExcept(x): if x < 0.: raise NegativeArgument() # This reports failure else: return np.sqrt(x) xValues = [4, 3., 0., -2.] # test numbers print("\n The Nan version:") for x in xValues: y = myRootNaN(x) if np.isnan(y): outLine = "The number x = {x:7.2f} does not have a square root" outLine = outLine.format(x=x) else: outLine = "The square root of {x:7.2f} is {y:8.3f}" outLine = outLine.format(x=x, y=y) print(outLine) print("\n The None version:") for x in xValues: y = myRootNone(x) if (y != None): outLine = "The square root of {x:7.2f} is {y:8.3f}" outLine = outLine.format(x=x, y=y) else: outLine = "The number x = {x:7.2f} does not have a square root" outLine = outLine.format(x=x) print(outLine) print("\n The Try, Except, Else, Finally version:") for x in xValues: try: y = myRootExcept(x) except NegativeArgument: outLine = "The number x = {x:7.2f} does not have a square root" outLine = outLine.format(x=x) else: outLine = "The square root of {x:7.2f} is {y:8.3f}" outLine = outLine.format(x=x,y=y) finally: print(outLine) """ (three quotes start and end a multi-line comment) Should produce: The square root of 4.00 is 2.000 The square root of 3.00 is 1.732 The square root of 0.00 is 0.000 The number x = -2.00 does not have a square root """