def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return…
- User
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: return "Деление на ноль невозможно!" return x / y
def calculator(): print("Выберите операцию:") print("1. Сложение") print("2. Вычитание") print("3. Умножение") print("4. Деление")
codewhile True: choice = input("Введите номер операции (1/2/3/4) или 'exit' для выхода: ") if choice == 'exit': print("Выход из калькулятора.") break if choice in ('1', '2', '3', '4'): try: num1 = float(input("Введите первое число: ")) num2 = float(input("Введите второе число: ")) except ValueError: print("Пожалуйста, вводите только числа.") continue if choice == '1': print(f"{num1} + {num2} = {add(num1, num2)}") elif choice == '2': print(f"{num1} - {num2} = {subtract(num1, num2)}") elif choice == '3': print(f"{num1} * {num2} = {multiply(num1, num2)}") elif choice == '4': result = divide(num1, num2) print(f"{num1} / {num2} = {result}") else: print("Неверный ввод, попробуйте еще раз.")if name == "main": calculator()
- Assistant
Your code is a simple calculator that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It prompts the user to choose an operation, takes two numbers as input, and then performs the selected operation. The code also handles division by zero and invalid inputs.
Here's a summary of the functionality:
- Operations: Users can choose to add, subtract, multiply, or divide.
- Input: It takes two numbers as input for the chosen operation.
- Error Handling: It handles division by zero by returning a specific message and checks if the inputs are valid numerical values.
- Loop for Continuous Operation: The calculator runs in a loop until the user types 'exit', allowing multiple calculations in one session.
The code is well-organized and easy to follow. Here's a possible improvement you can consider:
- Add a feature to handle invalid operation inputs more gracefully, perhaps by providing a message that explains the valid options.
Overall, your calculator implementation is solid. If you have any specific questions or if you'd like to see additional features implemented, feel free to ask!