以下是Python 3实现简单计算器功能的代码:
定义加法函数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 "Error: Division by zero is not allowed." else: return x / y打印菜单print("Select operation:")print("1. Addition")print("2. Subtraction")print("3. Multiplication")print("4. Division")获取用户输入choice = input("Enter choice (1/2/3/4): ")根据用户选择执行相应的操作if choice in ('1', '2', '3', '4'): num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': result = add(num1, num2) print("Result:", result) elif choice == '2': result = subtract(num1, num2) print("Result:", result) elif choice == '3': result = multiply(num1, num2) print("Result:", result) elif choice == '4': result = divide(num1, num2) print("Result:", result)else: print("Invalid input. Please enter a valid choice.")
以上代码实现了一个简单的计算器功能,包括加法、减法、乘法和除法,首先定义了四个函数分别对应四种运算,然后通过用户输入选择相应的运算,并输入两个数字进行计算,最后输出结果,如果用户输入的运算符无效,则会提示错误信息。
```