Python货币转换

电脑技术 电脑技术 1331 人阅读 | 1 人回复 | 2022-04-14

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
https://www.geeksforgeeks.org/currency-converter-in-python/

回答|共 1 个

willsonlincake 发表于 2022-4-14 18:21:48| 字数 769 来自手机 | 显示全部楼层

import requests
  
class Currency_convertor:
    # empty dict to store the conversion rates
    rates = {}
    def __init__(self, url):
        data = requests.get(url).json()
  
        # Extracting only the rates from the json data
        self.rates = data["rates"]
  
    # function to do a simple cross multiplication between
    # the amount and the conversion rates
    def convert(self, from_currency, to_currency, amount):
        initial_amount = amount
        if from_currency != 'EUR' :
            amount = amount / self.rates[from_currency]
  
        # limiting the precision to 2 decimal places
        amount = round(amount * self.rates[to_currency], 2)
        print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency))
  
# Driver code
if __name__ == "__main__":
  
    # YOUR_ACCESS_KEY = 'GET YOUR ACCESS KEY FROM fixer.io'
    url = str.__add__('http://data.fixer.io/api/latest?access_key=', YOUR_ACCESS_KEY)  
    c = Currency_convertor(url)
    from
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

热门推荐