gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)
create a python code for a calculator
- User
create a python code for a calculator
- Assistant
Sure! Here's a simple code for a calculator that can perform basic arithmetic operations (+, -, *, /) on two numbers:
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): if b != 0: return a / b else: return "Error: Cannot divide by zero." print("Welcome to the Calculator!") print("Choose an operation:") print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice = input("Enter your choice (1/2/3/4): ") num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the 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': print(num1, "/", num2, "=", divide(num1, num2)) else: print("Invalid input. Please choose a valid option (1/2/3/4).")You can run this code in any Python IDE or a command prompt to perform calculations based on your inputs.