如何摆脱无限循环

时间:2015-03-19 01:09:59

标签: python

你在一家出售两种食品的面包店工作:松饼和蛋糕。在任何给定时间,您店内的松饼和蛋糕的数量都存储在为您定义的变量松饼和蛋糕中。 编写一个程序,从标准输入中获取字符串,表明客户正在购买的产品("松饼"用于松饼,"蛋糕"用于蛋糕)。如果他们买松饼,减少一个松饼,如果他们买了一个蛋糕,减少2个蛋糕。如果没有剩下的烤好的东西,打印("缺货")。 一旦你完成销售,输入" 0" ,并打开程序打印剩余的松饼和蛋糕的数量,形式为#34;松饼:9个蛋糕:3" (例如,如果剩下9个松饼和3个蛋糕)。

to_buy=input()
while to_buy != "0":
if to_buy==muffins and muffins>0:

    muffins-=1
else:
    print("Out of stock")
if to_buy==cupcakes and cupcakes>0:

    cupcakes-=1
else:
    print("Out of stuck")
print("muffins:",muffins,"cupcakes:",cupcakes)

以上是我写的问题和代码。当我尝试运行它时,代码一直进入无限循环,我不知道为什么。

3 个答案:

答案 0 :(得分:1)

  

代码一直进入无限循环,我不知道为什么。

to_buy=input()
while to_buy != "0":

您永远不会更改to_buy,因此循环会无限期地继续。例如,假设to_buy为“3”。然后while循环条件为True,因此执行进入while循环。但是在while循环中to_buy永远不会改变,所以while循环一遍又一遍地执行。

要解决这个问题,您可以这样做:

while True:  #Infinite loop

    to_buy = input()
    if to_buy == "0": break  #Terminate the infinite loop

    #Rest of code here

答案 1 :(得分:0)

这一行:to_buy=input()

必须位于loop

变量to_buy在循环时从未改变它的值..因此,它不会退出循环,而是导致 无限循环

以退出循环。您必须更改变量to_buy的值。

为了做到这一点。

  

您必须将输入放在循环中

我还建议使用do while,因此它将首先处理输入

答案 2 :(得分:0)

to_buy=input()
while to_buy != "0":
    if to_buy=="muffin":
        if muffins>0:
            muffins-=1
        else:
            print("Out of stock")
    if to_buy=="cupcake":
        if cupcakes>0:
            cupcakes-=1
        else:
            print("Out of stock")
    to_buy=input()
print("muffins:", muffins, "cupcakes:", cupcakes)