Python循环不能正确返回,我该如何修改?(Python loop keeps returning incorrectly, how can I amend this? [duplicate])
这个问题在这里已经有了答案:
为什么一个变量对多个值的不等式检查总是返回true? 3个答案 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!即使选择变量是正确的。 我应该做些什么编辑才能打印总成本?
This question already has an answer here:
Why non-equality check of one variable against many values always returns true? 3 answers 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)This code keeps returning
Unfortunately, that is not a valid choice! Please pick again and remember to capitalise the first letter!even when the choice variable is correct. What edits should I make to make it print the total cost?
最满意答案
看看你的逻辑:
if choice != A or choice != B ...choice只能匹配一个硬编码的选项; 对于任何choice值,此测试必须为True 。 相反,尝试类似的东西
if choice not in ["Baguette", "Bagel", "Sub", ...]:更好的是,使用你已经拥有的列表:
if choice not in sandwiches:Look at your logic:
if choice != A or choice != B ...choice can match only one of your hard-coded alternatives; this test must be True for any value of choice. Instead, try something like
if choice not in ["Baguette", "Bagel", "Sub", ...]:Better yet, use the list you already have:
if choice not in sandwiches:更多推荐
发布评论