实现计算器的四则运算功能python
时间: 2024-06-12 17:08:47 浏览: 122
您可以使用以下代码实现计算器的四则运算功能:
```python
def calculator():
a = input("请输入第一个数:")
b = input("请输入第二个数:")
operator = input("请输入要执行的四则运算 (+-*/):")
if operator not in ['+', '-', '*', '/']:
print('运算符输入有误')
elif not a.isdigit() or not b.isdigit():
print('数值输入有误,请按要求输入')
else:
a = int(a)
b = int(b)
if operator == '+':
result = a + b
elif operator == '-':
result = a - b
elif operator == '*':
result = a * b
else:
if b == 0:
print('除数不能为0')
return
result = a / b
print(f'{a} {operator} {b} = {result}')
calculator()
```
阅读全文