汇率兑换程序python
时间: 2024-01-05 09:14:00 浏览: 120
下面是一个简单的汇率兑换程序的 Python 代码示例:
```python
import requests
def exchange_rate(amount, from_currency, to_currency):
url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
response = requests.get(url)
data = response.json()
try:
rate = data['rates'][to_currency]
converted_amount = amount * rate
return converted_amount, to_currency
except KeyError:
return "Invalid currency code. Please try again."
```
使用方法:
```python
amount = 100
from_currency = "USD"
to_currency = "EUR"
result = exchange_rate(amount, from_currency, to_currency)
print(f"{amount} {from_currency} is equivalent to {result[0]} {result[1]}")
```
输出结果:
```
100 USD is equivalent to 83.99 EUR
```
这个程序使用了 Exchange Rates API,它提供了实时的汇率数据。你需要在该网站注册并获得一个 API 密钥,然后将其替换到代码中。另外,请注意,该 API 每个月只提供有限的免费查询次数。
阅读全文