Advertisement

python美元汇率兑换程序代码_如何实现python汇率转换代码

阅读量:

对于那些刚开始学习Python的朋友们来说,在编程世界里最让人感到困惑的就是那些基础功能的实现代码了。尽管这些功能各有不同但许多函数虽然功能不同却都能达到类似的效果。今天为大家带来了编写能够转换货币汇率的Python代码实例希望对大家有所帮助。

Python中的货币转换器

tkinter – 用于用户界面(UI)requests – 获取网址

货币转换器的python构建步骤实时汇率

导入所需的库

CurrencyConverter类

货币转换器的用户界面

主函数

一、实时汇率

The base currency is US dollar, which implies that any currency conversion must first be converted to this base before being converted into another currency. This implies that converting any currency requires first converting it to the base currency, which is US dollar, and then converting from the base currency to the target currency.

Date and time:显示上次更新的日期和时间。

Rates:这是基础货币与美元的货币汇率。

二、导入我们需要的库

我们使用tkinter和request库。因此,我们需要导入库。import requests

from tkinter import *import tkinter as tk

from tkinter import ttk

三、创建CurrencyConverter类

接下来,我们将生成CurrencyConverter类,并基于实时汇率执行货币转换操作以输出转换后的金额

1、让我们创建class的构造函数class RealTimeCurrencyConverter():

def init(self, url):
将数据字段通过从指定URL执行HTTP GET请求并解析为JSON格式后的结果赋值给self.data;
将汇率字段设置为从JSON数据中提取的'rates'字段。

request.get(url)会向我们的python应用程序响应,并通过.json()方法解析页面内容为json文件。我们将其解析结果存储于数据变量中。

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

此方法采用以下参数:

From_currency:需要转换的货币

to _currency: 想要转换成的货币

Amount:需要转换的金额

并返回转换后的金额

例如:url = 'https://api.exchangerate-api.com/v4/latest/USD'

converter = RealTimeCurrencyConverter(url)

print(converter.convert('CNY','USD',100))

小伙伴们可以选择存储哦~如果有类似的实际需求可以直接套用的场景的话。如需了解更多Python实用知识的丰富内容,请访问云海天Python教程网的链接即可。

全部评论 (0)

还没有任何评论哟~