新聞中心
Python中的貨幣轉(zhuǎn)換器

tkinter – 用于用戶界面(UI)requests – 獲取網(wǎng)址
python匯率轉(zhuǎn)換步驟
-
實時匯率
-
導(dǎo)入所需的庫
-
CurrencyConverter類
-
貨幣轉(zhuǎn)換器的用戶界面
-
主函數(shù)
一、實時匯率
Base – USD:這意味著我們有基準貨幣美元。這意味著要轉(zhuǎn)換任何貨幣,我們必須先將其轉(zhuǎn)換為USD,然后再由USD轉(zhuǎn)換為任意貨幣。
Date and time:顯示上次更新的日期和時間。
Rates:這是基礎(chǔ)貨幣與美元的貨幣匯率。
二、導(dǎo)入我們需要的庫
我們使用tkinter和request庫。因此,我們需要導(dǎo)入庫。
import requests from tkinter import *import tkinter as tk from tkinter import ttk
三、創(chuàng)建CurrencyConverter類
現(xiàn)在,我們將創(chuàng)建CurrencyConverter類,該類將獲取實時匯率并轉(zhuǎn)換貨幣并返回轉(zhuǎn)換后的金額。
1、讓我們創(chuàng)建class的構(gòu)造函數(shù)
class RealTimeCurrencyConverter(): def __init__(self,url): self.data = requests.get(url).json() self.currencies = self.data['rates']
equests.get(url)將頁面加載到我們的python程序中,然后.json()會將頁面轉(zhuǎn)換為json文件。我們將其存儲在數(shù)據(jù)變量中。
2、Convert()方法:
def convert(self, from_currency, to_currency, amount): initial_amount = amount if from_currency != 'USD' : amount = amount / self.currencies[from_currency] # limiting the precision to 4 decimal places amount = round(amount * self.currencies[to_currency], 4) return amount
此方法采用以下參數(shù):
From_currency:需要轉(zhuǎn)換的貨幣
to _currency: 想要轉(zhuǎn)換成的貨幣
Amount:需要轉(zhuǎn)換的金額
并返回轉(zhuǎn)換后的金額
例如:
url = 'https://api.exchangerate-api.com/v4/latest/USD'
converter = RealTimeCurrencyConverter(url)
print(converter.convert('CNY','USD',100))小伙伴們可以保存起來了,有類似上述實戰(zhàn)需求可以直接套用哦~如需了解更多python實用知識,點擊進入PyThon學(xué)習網(wǎng)教學(xué)中心。
(推薦操作系統(tǒng):windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。)
網(wǎng)頁名稱:創(chuàng)新互聯(lián)Python教程:如何實現(xiàn)python匯率轉(zhuǎn)換代碼
轉(zhuǎn)載來源:http://www.dlmjj.cn/article/dpcjeej.html


咨詢
建站咨詢
