gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
write the calculator code in python
- User
write the calculator code in python
- Assistant
Here's a simple calculator program in Python that can perform addition, subtraction, multiplication, and division:
# define a function for each operation def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: raise ValueError('Cannot divide by zero') return x / y # get user input for the operation and numbers print('Select operation:') print('1. Add') print('2. Subtract') print('3. Multiply') print('4. Divide') choice = input('Enter choice (1/2/3/4): ') num1 = float(input('Enter first number: ')) num2 = float(input('Enter second number: ')) # perform the calculation based on user choice 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': print(num1, '/', num2, '=', divide(num1, num2)) else: print('Invalid input')This code first defines four functions for addition, subtraction, multiplication, and division, each taking two arguments and returning the result of the corresponding operation. It then prompts the user to enter the operation and the two numbers, converts them to float values, and calls the appropriate function to perform the calculation. Finally, it prints the result. The code also includes error handling for division by zero.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.