# # Demonstrate exceptions with some arithmetic. # import math # # Safely read a floating-point value so that it doesn't crash if the user # enters something non-numeric. # # Parameters: # prompt: The prompt to display before reading the value # # Returns: A floating-point number entered by the user. # def safeRead(prompt): done = False while done == False: try: a = float(input(prompt)) done = True except ValueError: print("That wasn't numeric. Try again...") return a # # Demonstrate the safe read function # a = safeRead("Enter the value for a: ") b = safeRead("Enter the value for b: ") # # Demonstrate the use of other exceptions # print(a, "+", b, "=", a+b) print(a, "-", b, "=", a-b) print(a, "*", b, "=", a*b) try: print(a, "/", b, "=", a/b) except ZeroDivisionError: # Catch an attempt to divide by 0 print("Couldn't compute", a, "/", b, "because the denominator is 0.") try: print("log(", a, ") =", math.log(a)) asdf() # this function doesn't exist except ValueError: # Catch an attempt to compute log of 0 or negative print("Can't compute log of a value less than or equal to zero.") except: # Catch any type of exception (in this case the NameError that occurs # when attempting to call a function that doesn't exist) print("Opps, something went wrong!")