Python循环不能正确返回,我该如何修改?

时间:2018-01-17 21:16:59

标签: python python-3.x loops

sandwichType=""
totalCost=0
sandwiches=["Baguette", "Bagel", "Sub", "Wrap", "White"]
sandwichVAL={"Baguette":3.50, "Bagel":2.10, "Sub":3.99, "Wrap":4.15, "White":0.90}
choice=""
while choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White":
  choice=str(input("What type of sandwich would you like?\n>Baguette - £3.50\n>Bagel    - £2.10\n>Sub      - £3.99\n>Wrap     - £4.15\n>White    - £0.90\n"))
  if choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White":
    print("Unfortunately, that is not a valid choice! Please pick again and remember to capitalise the first letter!")
  else:
    print()
totalCost+=sandwichVAL[choice]
print(totalCost)

此代码不断返回

Unfortunately, that is not a valid choice! Please pick again and remember to capitalise the first letter!

即使选择变量是正确的。我应该做什么编辑才能打印出总费用?

3 个答案:

答案 0 :(得分:3)

if choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White":

这个逻辑不正确。当这些表达式的任何为真时,将采用该分支。例如如果choice = "Bagel",则(choice != "Sub") == True

您可能需要and而不是or s。更好的是,既然你已经定义了一个有效的三明治列表,你可以写:

if choice not in sandwiches:

答案 1 :(得分:1)

看看你的逻辑:

if choice != A or choice != B ...

choice只能匹配一个的硬编码替代品;对于True的任何值,此测试必须<{em> choice。 相反,尝试像

这样的东西
if choice not in ["Baguette", "Bagel", "Sub", ...]:

更好的是,使用您已有的列表:

if choice not in sandwiches:

答案 2 :(得分:1)

您只需通过以下方式检查选择是否有效:

if choice not in sandwiches:
    print("Unfortunately, ...")