【发布时间】:2019-10-30 22:17:59
【问题描述】:
因此,我编写了一个购物篮,并在输入一些项目后打印 elif 语句,例如“火腿”。为什么?
我已经尝试将 while 循环添加到项目列表中,但这没有奏效。
print("What would you like? We have:")
## A function to call anywhere throughout the code to be able to print
the item list
def item_List():
print(" - Milk")
print(" - Bread")
print(" - Butter")
print(" - Salt")
print(" - Pepper")
print(" - Ham")
print(" - Steak")
print(" - Banana Bunch")
print(" - Apple Tray")
print(" - Grapes")
print(" - Winegums")
print(" - Black Jacks")
print(" - Sugar")
print(" - Honey")
print(" - Tea Bags")
print(" - Coffee")
()
## Function caller
item_List()
## Variable set to a list for future appends
items = []
total = 0
addmore = True
while addmore == True:
print("Add an item or type stop.")
userInput = input()
if userInput.lower() == "stop":
addmore = False
else:
if userInput.lower() == "milk":
total += 1.55
if userInput.lower() == "bread":
total += 1.82
if userInput.lower() == "butter":
total += 1.29
if userInput.lower() == "salt":
total += 1.20
if userInput.lower() == "pepper":
total += 1.20
if userInput.lower() == "ham":
total += 1.99
if userInput.lower() == "steak":
total += 3.99
if userInput.lower() == "banana bunch":
total += 2.25
if userInput.lower() == "apple tray":
total += 1.52
if userInput.lower() == "grapes":
total += 1.41
if userInput.lower() == "winegums":
total += 0.85
if userInput.lower() == "black jacks":
total += 0.85
if userInput.lower() == "sugar":
total += 2.95
if userInput.lower() == "honey":
total += 0.85
if userInput.lower() == "tea":
total += 2.85
if userInput.lower() == "coffee":
total += 3.05
elif userInput not in items:
print("Please enter a valid item.")
## List append for user to change their shopping basket by adding items
to their basket
items.append(userInput)
print("Item added. Basket Total:","£",round(total,3))
## This prints the of their basket/list
print("\n--- Your Shopping List ---")
for i in items:
print(i.title())
## This prints the total of their basket/list
print("Total: £"+str(total))
输出不应显示“请输入一个有效的项目”,它应该只是添加该项目并要求另一个输入。
【问题讨论】:
-
elif仅适用于您的 lastif子句 -
items是您的购物清单,而不是可用商品的清单。逻辑不正确。 -
您的条件是“如果该商品不是咖啡,并且它不在您的购物篮中,则它是无效商品”。
标签: python if-statement