# # Demonstrate catching exceptions in Python # # # Read a floating-point value from the user in a safe manner, looping back # to read another value if something non-numeric was entered. # # Parameters: # prompt: The prompt to display before reading the value (defaults to the # empty string). # # Returns: A floating-point value read from the user. # def safeInput(prompt = ""): # The input is not valid until a valid value is entered valid_input = False # Loop until a valid value is entered. while valid_input == False: try: # Read the value from the user. num = float(input(prompt)) # Mark that a valid value was read successfully. valid_input = True except ValueError: # Report that the input was not valid. print("That wasn't numeric... Try again...") # Return the value entered by the user. return num # # Read two values safely. # a = safeInput("Enter a number: ") b = safeInput("Enter another number: ") # # Demonstrate how a division by zero error can be caught. # try: print(a, "+", b, "=", a + b) print(a, "-", b, "=", a - b) print(a, "*", b, "=", a * b) print(a, "/", b, "=", a / b) print("Something else...") except ZeroDivisionError: print(a, "/", b, "couldn't be performed because the denoninator is 0.") except: print("Something went wrong...") quit() # # Show that the program continues to execute after the except blocks. # print("Here's the rest of the program...")