Python循环一直错误地返回,我如何修改它?

2024-09-26 18:05:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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!

即使选择变量是正确的。我应该做什么编辑才能打印出总成本?你知道吗


Tags: orthatisnotprintwhitewrapchoice
3条回答
if choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White":

这个逻辑是错误的。当这些表达式中的任何为真时,将执行分支。e、 如果choice = "Bagel",那么(choice != "Sub") == True。你知道吗

您可能需要and而不是ors。更好的是,因为您已经定义了一个有效三明治列表,您可以编写:

if choice not in sandwiches:

看看你的逻辑:

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

choice只能匹配硬编码备选方案中的一个;对于choice的任何值,此测试必须是True。 相反,你可以试试

if choice not in ["Baguette", "Bagel", "Sub", ...]:

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

if choice not in sandwiches:

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

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

相关问题 更多 >

    热门问题