Python循环不断返回错误,我如何修改它?
此代码不断返回Python循环不断返回错误,我如何修改它?,python,python-3.x,loops,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
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!
这种逻辑是错误的。当这些表达式中的任何一个为真时,将执行分支。e、 g.如果choice=“Bagel”
,则(choice!=“Sub”)==True
您可能需要和
s而不是或
s。更好的是,由于您已经定义了有效三明治的列表,您可以写:
if choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White":
这种逻辑是错误的。当这些表达式中的任何一个为真时,将执行分支。e、 g.如果choice=“Bagel”
,则(choice!=“Sub”)==True
您可能需要和
s而不是或
s。更好的是,由于您已经定义了有效三明治的列表,您可以写:
if choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White":
看看你的逻辑:
if choice not in sandwiches:
选项
只能匹配一个硬编码的备选方案;对于选项的任何值
,此测试必须为真
。
相反,尝试类似的方法
if choice != A or choice != B ...
更好的方法是使用您已有的列表:
if choice not in ["Baguette", "Bagel", "Sub", ...]:
看看你的逻辑:
if choice not in sandwiches:
选项
只能匹配一个硬编码的备选方案;对于选项的任何值
,此测试必须为真
。
相反,尝试类似的方法
if choice != A or choice != B ...
更好的方法是使用您已有的列表:
if choice not in ["Baguette", "Bagel", "Sub", ...]:
您只需通过以下方式检查选择是否有效:
if choice not in sandwiches:
您只需通过以下方式检查选择是否有效:
if choice not in sandwiches:
你的逻辑是错误的。如果其中任何一个条件为
True
,则或
条件返回True
。您应该将或
s更改为和
s。但更好的是,在中使用。呃,这个评论越来越长了,我会写一个答案。编辑:有很多人打败了我。此外,您没有列出三明治列表-dictsandwichVAL
就足够了。您的逻辑是错误的。如果其中任何一个条件为True
,则或
条件返回True
。您应该将或
s更改为和
s。但更好的是,在
中使用。呃,这个评论越来越长了,我会写一个答案。编辑:有很多人打败了我。此外,您不需要列出三明治列表-dictsandwichVAL
就足够了。