python的计算器
时间: 2024-10-29 12:14:52 浏览: 4
Python的计算器功能可以很简单地通过编写一些基本的算术运算函数或者使用内置的`eval()`函数来实现。如果你想要创建一个命令行交互式的简单计算器,你可以这样做:
```python
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 x / y
else:
print("Error! Division by zero is not allowed.")
return None
print("Select operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter 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':
result = divide(num1, num2)
if result is not None:
print(num1, "/", num2, "=", result)
else:
print("Invalid input.")
阅读全文