Python之人民币与美元的换算
类别:荣誉资质 日期:2023-08-28 09:12:46
你可以使用外汇牌价来进行人民币和美元的双向换算。以下是一个简单的示例代码:
```python
import requests
def convert_currency(amount, from_currency, to_currency):
# 获取实时汇率
url=f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
response=requests.get(url)
data=response.json()
exchange_rate=data["rates"][to_currency]
# 进行换算
result=amount * exchange_rate
return result
# 示例:将100人民币换算成美元
amount_rmb=100
from_currency="CNY"
to_currency="USD"
result_usd=convert_currency(amount_rmb, from_currency, to_currency)
print(f"{amount_rmb} {from_currency}={result_usd} {to_currency}")
# 示例:将100美元换算成人民币
amount_usd=100
from_currency="USD"
to_currency="CNY"
result_cny=convert_currency(amount_usd, from_currency, to_currency)
print(f"{amount_usd} {from_currency}={result_cny} {to_currency}")
```
注意:这只是一个简单示例,实际应用中可能需要考虑更多因素,如手续费、汇率波动等。另外,使用外部API获取汇率需要联网,请确保你的网络连接正常。