【问题标题】:How do I loop an if statement until needed and then stop如何循环 if 语句直到需要然后停止
【发布时间】:2022-01-14 23:58:04
【问题描述】:

我想循环我的驱动程序代码,并在完成后询问用户是否要将另一种货币转换为 MYR。每次循环,将返回的金额保存到一个数组中,一旦用户没有更多的货币,他们就需要转换。该程序将把数组中的变量加在一起以产生总和并打印出来。如果需要,将这笔款项兑换成另一种货币。

类 Currency_convertor:

rates = {} 
def __init__(self, url):
    data = requests.get(url).json()


    self.rates = data["rates"] 
    
def convert(self, from_currency, to_currency, amount):
    initial_amount = amount
    if from_currency != 'EUR' :
        amount = amount / self.rates[from_currency]

    
    amount = round(amount * self.rates[to_currency], 2)
    print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency))
    return amount 

驱动代码

if __name__ == "__main__":

  YOUR_ACCESS_KEY = ''
  url = 'https://api.exchangerate-api.com/v4/latest/USD'
  c = Currency_convertor(url)
  from_country = input("From Country: ")
  to_country = input("TO Country: ")
  amount = int(input("Amount: "))

  returnedamount=c.convert(from_country, to_country, amount)

【问题讨论】:

  • 不要将您的访问密钥添加到您的问题中,密钥不应在您的任何代码上可见。
  • 如果这是你真正的访问密钥,你应该立即轮换它。

标签: python loops for-loop if-statement


【解决方案1】:

使用 while 语句。

例子:

x = 0

while x < 10:
    # This will keep running until the condition is no longer True
    print(x)
    x += 1

# Then run any final stuff outside of the loop
print('Finished looping')

【讨论】:

    【解决方案2】:

    使用“While”而不是“if”

    【讨论】:

      猜你喜欢
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 2021-06-30
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      相关资源
      最近更新 更多