我正在研究MyProgrammingLab问题,该问题说明如下:
你在一家出售两种食品的面包店工作:松饼和蛋糕。在任何给定时间,您店内的松饼和蛋糕的数量都存储在为您定义的变量松饼和蛋糕中。 编写一个程序,从标准输入中获取字符串,表明客户正在购买的产品("松饼"用于松饼,"蛋糕"用于蛋糕)。如果他们买松饼,减少一个松饼,如果他们买了一个蛋糕,减少一个蛋糕。如果没有更多的烘焙食品,请打印("缺货")。
一旦你完成销售,输入" 0",然后让程序打印出剩余的松饼和蛋糕的数量,形式为#34;松饼:9个蛋糕:3" (例如,如果剩下9个松饼和3个蛋糕)。
我在jGRASP中测试我的代码(不是一个粉丝,不幸的是课程需要)并且该程序按预期工作,但它似乎有时会提前终止,我正在努力找出原因,因为我在我的逻辑中找不到任何错误。这就是我所拥有的:
muffins = 5
cupcakes = 6
buyItem = raw_input("")
while buyItem == "m":
if muffins <= 0:
if cupcakes <= 0:
print("All out of stock.")
break
else:
print("Out of stock.")
buyItem = raw_input("")
else:
muffins -= 1
print("muffins: {} cupcakes: {}".format(muffins, cupcakes))
buyItem = raw_input("")
while buyItem == "c":
if cupcakes <= 0:
if muffins <=0:
print("All out of stock.")
break
else:
print("Out of stock.")
buyItem = raw_input("")
else:
cupcakes -= 1
print("muffins: {} cupcakes: {}".format(muffins, cupcakes))
buyItem = raw_input("")
这是一个早期终止的输出示例:
----jGRASP exec: python test.py
m
muffins: 4 cupcakes: 6
m
muffins: 3 cupcakes: 6
m
muffins: 2 cupcakes: 6
c
muffins: 2 cupcakes: 5
c
muffins: 2 cupcakes: 4
c
muffins: 2 cupcakes: 3
m
----jGRASP: operation complete.
但是,如果我输入的方式不同,它可以正常工作:
----jGRASP exec: python test.py
m
muffins: 4 cupcakes: 6
m
muffins: 3 cupcakes: 6
m
muffins: 2 cupcakes: 6
m
muffins: 1 cupcakes: 6
m
muffins: 0 cupcakes: 6
m
Out of stock.
c
muffins: 0 cupcakes: 5
c
muffins: 0 cupcakes: 4
c
muffins: 0 cupcakes: 3
c
muffins: 0 cupcakes: 2
c
muffins: 0 cupcakes: 1
c
muffins: 0 cupcakes: 0
c
All out of stock.
----jGRASP: operation complete.
我不确定是什么错。想法?
答案 0 :(得分:3)
因为一旦你离开while "m"
,你就无法回到那里。
while buyItem == "m":
#do stuff
while buyItem == "c":
#do other stuff
#end program
当您输入m -> c -> m
,m != c
时,我们离开while buyItem == "c":
并结束该计划。
我们应该有一个循环,并且如果我们有库存则只在最后请求输入一次,否则在完全缺货时突破循环。此外,由于您的作业仅表示输入为0
时打印:
muffins = 5
cupcakes = 6
buyItem = raw_input("")
while buyItem in ["m", "c", "0"]:
if buyItem == "m":
if muffins <= 0:
print("Out of stock.")
else:
muffins -= 1
elif buyItem == "c":
if cupcakes <= 0:
print("Out of stock.")
else:
cupcakes -= 1
elif buyItem == "0":
print("muffins: {} cupcakes: {}".format(muffins, cupcakes))
break
else: # input is not "m" or "c" or "0"
print(buyItem.join(" is not a valid input"))
break
if muffins <= 0 and cupcakes <= 0: # we can check this once at the end and break out if we are entirely out of stock
print("All out of stock.")
break
else: # otherwise, if we have some stock, ask for input
buyItem = raw_input("")