【问题标题】:Python : Amount input with WhilePython:使用 While 输入金额
【发布时间】:2021-05-07 09:19:08
【问题描述】:

这里是初学者。我正在尝试构建一个循环,其中 chekout 显示的总金额必须超过 0 美元。例如,如果我从 450$ 开始,则代码有效。但是如果我从 -12 开始,它会再次询问我(这就是我想要的),但是如果我输入 450 作为第三篇文章;第一个条件继续运行。这是为什么?提前致谢。

amount = input("What's the total amount of the bill ? :")
value = float(amount)

while (value < 0):
    print("Please enter an amount higher than 0$ !")
    amount = input("What's the total amount of the bill ? :")
    
else:
    print("Total amount of the bill:{0}".format(value))

【问题讨论】:

标签: python loops while-loop conditional-statements


【解决方案1】:

您忘记更新变量“值”,因此即使在输入 450(值仍为 -12)后,您的 while 循环条件仍然为真。您也可以在同一行中将输入转换为浮点数,这样就不需要“数量”变量

value = float(input("What's the total amount of the bill ? :"))

while (value < 0):
    print("Please enter an amount higher than 0$ !")
    value = float(input("What's the total amount of the bill ? :"))
    
else:
    print("Total amount of the bill:{0}".format(value))

【讨论】:

  • 感谢您的清晰解释!我很感激。
猜你喜欢
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多