Reciprocal Calculator

Write a program that asks the user for an integer and prints the reciprocal of that number. Implement exception handling for zero and non-integer inputs, and ensure that the user can continue to enter numbers until they enter a valid input.

Example 1:

Input: "5" 
Output: 0.2

Example 2:

Input: "0" (then "5") 
Output: "Error: You cannot take the reciprocal of zero. Please try again.", 0.2

Use the built-in int() function to convert the user’s input to an integer. Be sure to wrap the operation in a try/except block to handle potential exceptions.

def reciprocal_calculator():
    while True:
        try:
            number = int(input("Please enter an integer: "))
            return 1 / number
        except ValueError:
            print("Error: You did not enter a valid integer. Please try again.")
        except ZeroDivisionError:
            print("Error: You cannot take the reciprocal of zero. Please try again.")

print(reciprocal_calculator())

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!