虽然循环条件

虽然循环条件

问题描述:

这是一个非常基本的问题,我为它的简单性而道歉,但我一直在寻找答案,并尝试不同的语法几个小时没有运气。虽然循环条件

我正在使用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() 

出于某种原因,无论按键是否显示错误消息。 非常感谢您的帮助!

变化:

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

到:

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

正如Saish在下面的意见建议,这样做的一个更Python的方法是:

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

你的帮助是极大的赞赏!谢谢 – bdawg425 2014-09-11 05:14:52

+1

这样做的pythonic方式实际上是: 'while purpose.upper()not in(“C”,“D”):' – Saish 2014-09-11 05:18:00

+0

@Saish +1非常真实! (回答更新) – alfasin 2014-09-11 15:33:24

您需要将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"): 
+0

当用户输入'CD'时,最后一个选项将返回'True' :) – alfasin 2014-09-11 04:03:07

+0

@alfasin - 好点,我认为它是一个字符。我会解决它:P – sapi 2014-09-11 04:04:23

+0

非常感谢你的帮助! – bdawg425 2014-09-11 05:14:02

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

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 

让我知道它是如何工作

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"):