我刚刚开始使用Python,而我正在开发一个分配程序。描述是用于将附加到杂货车的电子设备。当购物者开始购物时,设备将询问购物者他们的预算,这是购物者想要花费的最大金额。然后它会要求购物者输入他们放在购物车中的每件商品的成本。每次将某些东西添加到购物车时,设备都会将该商品的成本添加到购物车中所有商品的运行总额或总和中。一旦所有物品的成本超过预算,它就会提醒购物者他们花了太多钱。
我已经绘制了代码,并找出了我需要做的所有事情。但我无法正确添加用户的多个输入。理想情况下,它应该将用户的第一个输入添加到第二个,第三个等,并在用户输入ALL DONE时停止。
到目前为止,这是我的代码。任何指针都将非常感谢!
budget = 0
itemCost = 0
cartTotal = 0
print ("Hello! Welcome to the best grocery store ever!")
budget = int (input ("What is your budget for today? "))
itemCost = int (input ("Please tell me the cost of the most recent item your cart. Print ALL DONE to quit " ))
while itemCost != "All DONE" and cartTotal <= budget:
itemCost = int (input ("Please tell me the cost of the most recent item your cart. Print ALL DONE to quit " )) #works
cartTotal = itemCost + itemCost
print ("OK, the items in your cart cost a total of ", cartTotal)
print ("Your budget is ", budget, " you have spent ", cartTotal, " you have ", budget - cartTotal, " left over.")
else:
print ("You are a horrible budgeter!")
答案 0 :(得分:-1)
所以检查输入是否为数字(.isdigit),如果是,则将其添加到运行总计中。你的代码不接受'ALL DONE',因为它只接受整数输入,所以我也改变了。最后,我已经将预算改为浮动,因为这会让我更有意义。希望这可以帮助!编辑:它不喜欢花车作为成本,但除了我测试它,它似乎工作
budget = 0
itemCost = 0
cartTotal = 0
on = "TRUE"
print("Hello! Welcome to the best grocery store ever!")
budget = float(input("What is your budget for today?"))
while on == "TRUE" :
itemCost = input("Please tell me the cost of the most recent item in your cart. Type ALL DONE to quit. ")
if itemCost == "ALL DONE" :
on = "FALSE"
elif itemCost.isdigit() :
cartTotal += float(itemCost)
if cartTotal < budget :
print("Ok, the items in your cart cost a total of ", cartTotal)
print ("Your budget is ", budget, " you have spent ", cartTotal, " you have ", budget - cartTotal, " left over.")
else :
print("You are a horrible budgeter!")
break
else :
print("Invalid entry!") #If neither a number nor ALL DONE was entered, this happens
continue