Build a Calculator app using Python

# Define a function to add two numbers
def addition(x, y):
    return x + y

# Define a function to subtract two numbers
def subtraction(x, y):
    return x - y

# Define a function to multiply two numbers
def multiplication(x, y):
    return x * y

# Define a function to divide two numbers
def division(x, y):
    return x / y

print("Welcome to the Calculator Program!")
print("Please select an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

while True:
    # Take input from the user
    user_choice = input("Enter your choice (1/2/3/4): ")

    # Check if the choice is valid
    if user_choice in ('1', '2', '3', '4'):
        try:
            number1 = float(input("Enter the first number: "))
            number2 = float(input("Enter the second number: "))
        except ValueError:
            print("Invalid input. Please enter a number.")
            continue

        if user_choice == '1':
            print(number1, "+", number2, "=", addition(number1, number2))
        elif user_choice == '2':
            print(number1, "-", number2, "=", subtraction(number1, number2))
        elif user_choice == '3':
            print(number1, "*", number2, "=", multiplication(number1, number2))
        elif user_choice == '4':
            if number2 == 0:
                print("Error! Division by zero is not allowed.")
            else:
                print(number1, "/", number2, "=", division(number1, number2))
        
        # Check if the user wants to perform another calculation
        next_calculation = input("Would you like to perform another calculation? (yes/no): ")
        if next_calculation.lower() != "yes":
            print("Thank you for using the calculator program. Goodbye!")
            break
    else:
        print("Invalid Input. Please enter a valid choice.")

Leave a comment