我有以下代码主要工作。我只需要它允许用户输入"加载项"直到他们输入sentinel值退出循环并让它添加选择。这是一个班级任务,但这是我遇到的所有困难。任何帮助将不胜感激。
#start
def main(): #create a module - python function to hold main processing
#declarations
addinArray = ["Whipped Cream", "Cinnamon", "Chocolate sauce", "Amaretto", "Irish whiskey"]
priceArray = [0.89, 0.25, 0.59, 1.50, 1.75] #this array holds the add-in prices
loopFlag = "" #sentinal value for looping
cnt = 0
COFFEECOST = 2 #constant to coffee cost
addinName = ""
totalCost = 0
#input enter add-in name
addinName = input("Enter on Keyboard Coffee Add-in (ex. Whipped Cream, Cinnamon, etc.) or Done to quit")
while (addinName != "Done"): #loop until addinName is Done
while (cnt < len(addinArray)):
if (addinName == addinArray[cnt]) :
totalCost = priceArray[cnt] + totalCost
print("Add-in ", addinName, " with a price of ", priceArray[cnt])
print( "with a total add-in price so far of ", totalCost)
cnt = cnt + 1 #increment counter for next element in array
#end while
addinName = input("Enter on Keyboard Coffee Add-in (ex. Whipped Cream, Cinnamon, etc.) or Done to quit")
#end while
totalCost = totalCost + COFFEECOST
print("Total cost is: ", totalCost)
main()
#stop
答案 0 :(得分:1)
我认为cnt = 0
应该在第一个循环后重置:
while (addinName != "Done"): #loop until addinName is Done
cnt = 0
如果没有这个,在第一个附加cnt可以达到len(addinArray)
并且永远不会在第二个while循环执行新附加组件之后。
答案 1 :(得分:0)
我在本地运行你的代码,我发现了两件事。
cnt
循环后将while
变量重置为零,否则它将不会再次执行,因为条件cnd>5
始终为true
input()
调用似乎引发了错误,因此我测试了raw_input()
并且似乎有效。
希望这有帮助!