循环条件

时间:2014-09-11 03:57:51

标签: python while-loop

这是一个非常基本的问题,我为它的简单而道歉,但我一直在寻找答案,并在没有运气的情况下尝试不同的语法。

我正在使用python为密码程序创建文本菜单。当按下无效键时,我使用while循环获取错误消息,但即使条件为false,它也会循环。

purpose = input("Type 'C' for coding and 'D' for decoding: ")

while purpose.upper() != "D" or "C":
    purpose = input("Error, please type a 'C' or a 'D': ")

if (purpose.upper() == "C"):
    do_something()

if (purpose.upper() == "D"):
    do_something()

出于某种原因,无论按键是什么,都会显示错误消息。 非常感谢你的帮助!

4 个答案:

答案 0 :(得分:3)

您需要将orand两边的条件视为逻辑上独立。

当计算机看到:

while purpose.upper() != "D" or "C":

它读作

(purpose.upper() != "D")

OR

"C"

仅第二部分"C"一直是真的。


你可能想要:

while purpose.upper() != "D" or purpose.upper() != "C":

或更好:

while purpose.upper() not in ("C", "D"):

答案 1 :(得分:1)

变化:

while purpose.upper() != "D" or "C":

为:

while purpose.upper() != "D" and purpose.upper() != "C":

正如Saish在下面的评论中所建议的那样,更为诡辩的方式是:

while purpose.upper() not in ("C", "D"):

答案 2 :(得分:0)

在这里试试这个。它似乎工作

 reason = ['D', 'C']
 while True:
     purpose = input("Type 'C' for coding and 'D' for decoding: ").upper()
     if reason.__contains__(purpose):
         print("You've got it this time")
         break

让我知道它是如何运作的

答案 3 :(得分:0)

while purpose.upper() != "D" or "C":

上述行将评估为:

while (purpose.upper() != "D") or "C":

表达式从左到右进行评估。在这里" C"永远是真的,因此总是执行循环。

你需要这样的东西:

while purpose.upper() != "D" or purpose.upper() != "C":

#You can put it all into a list ["C", "D"] and then check 
while purpose.upper() not in ["C", "D"]:

#You can put it all into a tuple ("C", "D") and then check 
while purpose.upper() not in ("C", "D"):