Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

Write python code for a simple calculator.

  1. User

    Write python code for a simple calculator.

  2. Assistant

    Here is an example of a simple calculator in Python:

    def add(a, b):
        return a + b
    
    def subtract(a, b):
        return a - b
    
    def multiply(a, b):
        return a * b
    
    def divide(a, b):
        return a / b
    
    print("Welcome to the calculator")
    
    while True:
        print("Please select operation -\n" \
            "1. Add\n" \
            "2. Subtract\n" \
            "3. Multiply\n" \
            "4. Divide\n" \
            "5. Exit\n")
    
        choice = input("Enter choice (1/2/3/4/5): ")
    
        if choice == '5':
            print("Exiting calculator...")
            break
    
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
    
        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))
    
        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))
    
        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))
    
        elif choice == '4':
            if num2 == 0:
                print("Error: Cannot divide by zero")
            else:
                print(num1, "/", num2, "=", divide(num1, num2))
    
        else:
            print("Invalid input")
    

    This code defines four functions for performing addition, subtraction, multiplication, and division. It then prompts the user to input which operation they would like to perform and two numbers to input into the operation. The program then checks the user's choice and performs the corresponding operation on the inputted numbers. If the user inputs 5, the program exits. If the user inputs an invalid input, the program prints an error message.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.