diff --git a/Code/Python/Calculator-Working.py b/Code/Python/Calculator-Working.py index 901c5a0..3edceb7 100644 --- a/Code/Python/Calculator-Working.py +++ b/Code/Python/Calculator-Working.py @@ -1,4 +1,4 @@ -# Program make a simple calculator +# Simple Calculator Program # This function adds two numbers def add(x, y): @@ -12,43 +12,54 @@ def subtract(x, y): def multiply(x, y): return x * y -# This function divides two numbers +# This function divides two numbers (with error handling) def divide(x, y): + if y == 0: + print("Error: Division by zero is not allowed.") + return None return x / y -print("Select operation.") -print("1.Add") -print("2.Subtract") -print("3.Multiply") -print("4.Divide") +print("===== Simple Calculator =====") +print("1. Add") +print("2. Subtract") +print("3. Multiply") +print("4. Divide") +print("=============================") while True: # take input from the user - choice = input("Enter choice(1/2/3/4): ") + choice = input("Enter choice (1/2/3/4): ") - # check if choice is one of the four options + # check if choice is valid if choice in ('1', '2', '3', '4'): - num1 = float(input("Enter first number: ")) - num2 = float(input("Enter second number: ")) + try: + num1 = float(input("Enter first number: ")) + num2 = float(input("Enter second number: ")) + except ValueError: + print("Invalid number! Please enter valid numeric values.\n") + continue if choice == '1': - print(num1, "+", num2, "=", add(num1, num2)) + print(f"{num1} + {num2} = {add(num1, num2)}") elif choice == '2': - print(num1, "-", num2, "=", subtract(num1, num2)) + print(f"{num1} - {num2} = {subtract(num1, num2)}") elif choice == '3': - print(num1, "*", num2, "=", multiply(num1, num2)) + print(f"{num1} * {num2} = {multiply(num1, num2)}") elif choice == '4': - print(num1, "/", num2, "=", divide(num1, num2)) - - # check if user wants another calculation - # break the while loop if answer is no - next_calculation = input("Let's do next calculation? (yes/no): ") + result = divide(num1, num2) + if result is not None: + print(f"{num1} / {num2} = {result}") + + # ask user for next calculation + next_calculation = input("Do you want to perform another calculation? (yes/no): ").lower() if next_calculation == "no": - break - + print("Exiting calculator... Goodbye!") + break + print() + else: - print("Invalid Input") + print("Invalid input! Please select a valid operation.\n")