溫馨提示×

Python怎么實現(xiàn)匯率轉換

小億
282
2023-08-18 03:56:54
欄目: 編程語言

Python可以使用外部的API或庫來實現(xiàn)匯率轉換。

一種常用的方法是使用forex-python庫。首先,需要安裝該庫,可以使用以下命令:

pip install forex-python

然后,通過以下代碼片段來實現(xiàn)匯率轉換:

from forex_python.converter import CurrencyRates
c = CurrencyRates()
amount = 1000
from_currency = "USD"
to_currency = "CNY"
conversion = c.convert(from_currency, to_currency, amount)
print(f"{amount} {from_currency} = {conversion} {to_currency}")

上述代碼中,我們首先導入CurrencyRates類,然后創(chuàng)建一個CurrencyRates對象c。接下來,我們指定要轉換的金額amount、原始貨幣from_currency和目標貨幣to_currency。最后,通過調(diào)用convert()方法來執(zhí)行實際的匯率轉換,并打印轉換結果。

另一種方法是使用外部的匯率轉換API。有很多免費的匯率轉換API可供使用,如exchangeratesapi.io。你可以使用requests庫來向API發(fā)送HTTP請求,并解析返回的JSON數(shù)據(jù)。

以下是一個使用exchangeratesapi.io的示例代碼:

import requests
amount = 1000
from_currency = "USD"
to_currency = "CNY"
url = f"https://api.exchangeratesapi.io/latest?base={from_currency}&symbols={to_currency}"
response = requests.get(url)
data = response.json()
conversion = data["rates"][to_currency] * amount
print(f"{amount} {from_currency} = {conversion} {to_currency}")

在上述代碼中,我們首先指定要轉換的金額amount、原始貨幣from_currency和目標貨幣to_currency。然后,我們構建一個API請求的URL,并使用requests.get()方法發(fā)送GET請求。接下來,我們解析返回的JSON數(shù)據(jù),并根據(jù)匯率計算轉換結果。最后,打印轉換結果。

請注意,使用外部的匯率轉換API需要有可靠的網(wǎng)絡連接,并且轉換結果可能會受到API的限制和實時匯率的波動影響。

0