用python代码写一个计算器
时间: 2023-11-20 14:05:34 浏览: 42
以下是一个简单的计算器实现,可以进行四则运算:
```python
def calculator():
num1 = float(input("请输入第一个数字:"))
op = input("请选择运算符(+、-、*、/):")
num2 = float(input("请输入第二个数字:"))
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
elif op == '/':
result = num1 / num2
else:
print("无效的运算符!")
return
print("计算结果为:", result)
calculator()
```
你可以直接运行上面的代码,并按照提示输入数字和运算符,即可得到计算结果。注意,这个计算器只能进行单次计算,要想进行多次计算,可以将代码放在一个循环中,或者使用函数递归调用。
相关问题
用python代码写一个简易计算器
以下是一个简单的Python代码实现基本计算器功能:
```python
# 定义计算函数
def calculator(num1, num2, operator):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
elif operator == "/":
return num1 / num2
else:
return "Invalid operator"
# 获取用户输入
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
operator = input("请输入运算符(+、-、*、/):")
# 进行计算
result = calculator(num1, num2, operator)
# 输出结果
print("计算结果为:", result)
```
运行代码后,用户可以输入两个数字和一个运算符(+、-、*、/),程序会根据运算符进行相应的计算,并输出结果。
用Python代码写一个汇率计算器
好的,以下是一个简单的汇率计算器的 Python 代码:
```python
import requests
def exchange_rate(from_currency, to_currency, amount):
url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
response = requests.get(url)
data = response.json()
exchange_rate = data["rates"][to_currency]
converted_amount = exchange_rate * amount
return converted_amount
print(exchange_rate("USD", "CNY", 100))
```
这个代码使用了 exchangerate-api.com 的 API 来获取汇率信息,然后计算出转换后的金额。你可以将 "USD" 和 "CNY" 替换成你需要的货币代码,以及将 100 替换成你需要转换的金额。
相关推荐
![](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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)