How to Code a Simple Calculator in Python?

Estimated read time 2 min read

Sure! Here’s an example of how you can code a simple calculator in Python:

def add(num1, num2):
    return num1 + num2

def subtract(num1, num2):
    return num1 - num2

def multiply(num1, num2):
    return num1 * num2

def divide(num1, num2):
    if num2 != 0:
        return num1 / num2
    else:
        return "Cannot divide by zero"

print("Welcome to the Simple Calculator!")

while True:
    print("Please select an operation:")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("5. Exit")

    choice = input("Enter your choice (1-5): ")

    if choice == "5":
        print("Thank you for using the Simple Calculator!")
        break

    num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))

    if choice == "1":
        result = add(num1, num2)
    elif choice == "2":
        result = subtract(num1, num2)
    elif choice == "3":
        result = multiply(num1, num2)
    elif choice == "4":
        result = divide(num1, num2)
    else:
        print("Invalid choice")
        continue

    print("Result: ", result)

In this code, the calculator provides a menu with options for addition, subtraction, multiplication, division, and exiting the program. The user is prompted to enter the numbers and choose an operation. The appropriate function is called based on the user’s choice, and the result is displayed.

You can expand this code to include more operations or add error handling for invalid input. Feel free to customize it according to your requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply