python写一个计算器
时间: 2023-10-09 17:16:35 浏览: 56
以下是一个简单的Python计算器程序,支持四则运算和幂运算:
```python
# 定义计算函数
def calculate(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
elif operator == '**':
return num1 ** num2
else:
return None
# 主程序
while True:
# 获取用户输入
num1 = float(input('请输入第一个数字:'))
operator = input('请输入运算符:')
num2 = float(input('请输入第二个数字:'))
# 调用计算函数
result = calculate(num1, num2, operator)
# 输出结果
if result is None:
print('无效的运算符')
else:
print('结果为:', result)
# 判断是否继续计算
choice = input('是否继续计算?(Y/N)')
if choice.upper() != 'Y':
break
```
运行程序后,输入数字和运算符,即可得到计算结果。程序会根据用户的选择,决定是否继续计算。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)