напиши код на питоне калькулятор
- User
напиши код на питоне калькулятор
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
напиши код на питоне калькулятор
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# Simple Calculator in Python
def add(x, y):
"""Add two numbers"""
return x + y
def subtract(x, y):
"""Subtract second number from first"""
return x - y
def multiply(x, y):
"""Multiply two numbers"""
return x * y
def divide(x, y):
"""Divide first number by second"""
if y == 0:
return "Error! Division by zero."
return x / y
def calculator():
print("Welcome to the Python Calculator!")
print("-------------------------------")
while True:
print("\nSelect operation:")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (×)")
print("4. Divide (÷)")
print("5. Quit")
choice = input("Enter choice (1/2/3/4/5): ")
if choice == '5':
print("Thank you for using the calculator. Goodbye!")
break
elif choice in ('1', '2', '3', '4'):
try:
num1 = float(input("\nEnter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numeric values.")
continue
if choice == '1':
result = add(num1, num2)
operation = '+'
elif choice == '2':
result = subtract(num1, num2)
operation = '-'
elif choice == '3':
result = multiply(num1, num2)
operation = '×'
elif choice == '4':
result = divide(num1, num2)
operation = '÷'
print(f"\nResult: {num1} {operation} {num2} = {result}")
else:
print("Invalid choice! Please select a valid operation.")
if __name__ == "__main__":
calculator()
This code provides a simple command-line calculator in Python that supports basic arithmetic operations: addition, subtraction, multiplication, and division. Here's how it works:
Functions for Operations: Each arithmetic operation is defined as a separate function (add, subtract, multiply, divide) for clarity and reusability.
User Interaction:
Input Validation:
Loop for Continuous Use:
while loop, allowing the user to perform multiple calculations until they choose to quit by selecting option 5.Clean Exit:
How to Run the Calculator:
Save the Code: Copy the code into a file named calculator.py.
Run the Program:
calculator.py is saved.python calculator.py (or python3 calculator.py depending on your Python installation).Use the Calculator:
Example Session:
Welcome to the Python Calculator!
-------------------------------
Select operation:
1. Add (+)
2. Subtract (-)
3. Multiply (×)
4. Divide (÷)
5. Quit
Enter choice (1/2/3/4/5): 1
Enter first number: 12
Enter second number: 8
Result: 12.0 + 8.0 = 20.0
Select operation:
1. Add (+)
2. Subtract (-)
3. Multiply (×)
4. Divide (÷)
5. Quit
Enter choice (1/2/3/4/5): 5
Thank you for using the calculator. Goodbye!
Feel free to enhance the calculator by adding more functions such as exponentiation, modulus, or even implementing advanced features like handling mathematical expressions.