用Python帮我写一个货币转换的代码
时间: 2024-06-08 11:01:16 浏览: 181
好的,以下是Python的货币转换代码:
```python
# 货币转换代码
def currency_converter(amount, from_currency, to_currency):
# 引入货币转换API
import requests
# 货币转换API的URL
url = 'https://api.exchangerate-api.com/v4/latest/%s' % from_currency
try:
# 发送HTTP请求,获取API的响应
response = requests.get(url)
data = response.json()
# 获取目标货币与源货币之间的汇率
exchange_rate = data['rates'][to_currency]
# 计算转换后的金额
converted_amount = amount * exchange_rate
# 返回转换后的金额
return converted_amount
except KeyError:
return "API中没有这种货币的汇率!"
```
你可以通过调用 currency_converter 函数,将指定的货币金额转换为另一种货币,例如:
```python
amount = 100.0
from_currency = 'USD'
to_currency = 'CNY'
converted_amount = currency_converter(amount, from_currency, to_currency)
print('%f %s = %f %s' % (amount, from_currency, converted_amount, to_currency))
```
这里将把100美元转换为人民币。
阅读全文