首页 > 解决方案 > Python:使用 While 输入金额

问题描述

初学者在这里。我正在尝试构建一个循环,其中结帐显示的总金额必须超过 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))

标签: pythonloopswhile-loopconditional-statements

解决方案


您忘记更新变量“值”,因此即使在输入 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))

推荐阅读