Python循环不能正确返回,我该如何修改?(Python loop keeps returning incorrectly, how can I amend this? [duplicate])

编程入门 行业动态 更新时间:2024-10-19 01:26:30
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:

更多推荐

本文发布于:2023-08-07 15:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我该   正确   loop   Python   amend

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!