from math import sqrt # Read a number, protecting the user from non-numeric input # Parameters: # prompt: The prompt to display before accepting input # Returns: A number entered by the user def readNumber(prompt): # Use the success variable to mark whether or not a number has been read # successfully success = False # Keep looping until a number is entered while success == False: try: a = float(input(prompt)) # If non-numeric input was entered then control jumps to the exception # handler. The success varuable is only set to True when a number # is entered success = True except ValueError: print("That input wasn't numeric. Enter the value again...") # Return the number entered by the user return a # Read two numbers from the user in a way that protects against non-numeric # input a = readNumber("Enter a number: ") b = readNumber("Enter another number: ") # Perform several basic arithmetic operations try: print(a,"+",b,"=",a+b) print(a,"-",b,"=",a-b) print(a,"*",b,"=",a*b) print(a,"/",b,"=",a/float(b)) except: # Display a nice error message if we attempt to divide by 0 print("You can't divide by 0.") try: print("sqrt(", a, ") = ", sqrt(a)) except ValueError: # Display a nice error message if we attempt to compute the square root of # a negative number print("You can't compute the square root of a negative number.") print("The rest of the program.")