2015-12-23 78 views
1

我不知道什么是问题,但是如果条件下有两个条件,我不能结束while循环。让我告诉代码:Python:无法在两个连续条件下终止“while”循环

while True: 
    k = input ("Please enter 'hello': ") 
    if k == "hello": 
     m = input ("Are your Sure? (Y/N): ") 
     if m == "Y" or "y" or "yes" or "Yes": 
      break 

现在,第二次提示后,即使我没有键入或任何其他事情,而循环仍然结束。我只想在第二次确认后结束它。在编码方面我的错误是什么?

+3

请正确缩进您的代码。 –

回答

1

它应该是这样的:

if m == "Y" or m == "y" or m == "yes" or m == "Yes":

5

这是内部发生。

您的代码:

m == "Y" or "y" or "yes" or "Yes" 

的Python解释:

(m == "Y")or ("y" or "yes") or "Yes" 

("y" or "yes")总是会产生y since it is not a falsey value然后("y" or "yes") or "Yes"改变这种"y" or "Yes"再次相同的值,从而最终(m == "Y")or ("y" or "yes") or "Yes"更改为(m == "Y")or "y"

为了避免这种情况,你可以使用单独检查所有条件或in作为BENC说

,甚至更简单

m.lower() in "yes" # Note that it also True if m is e or es or s etc.. 

     or 

"yes".startwith(m.lower()) # This work perfectly as per my test cases 
+1

upvoted for''是“.startwith(m.lower())'cool :) –

+0

@VivekSable谢谢你刚才想到的不同方式来做到这一点:P。 – The6thSense

1

变化or条件

演示

>>> while True: 
...  k = raw_input ("Please enter 'hello': ") 
...  if k == "hello": 
...   m = raw_input ("Are your Sure? (Y/N): ") 
...   if m == "Y" or m == "y" or m == "yes" or m == "Yes": 
...    break 
... 
Please enter 'hello': hello 
Are your Sure? (Y/N): y 
>>> 

我们可以使用lower字符串方法将字符串转换为小写,

演示

>>> m = raw_input ("Are your Sure? (Y/N): ").lower() 
Are your Sure? (Y/N): Yes 
>>> m 
'yes' 

注意

使用的raw_input()为Python 2 .x

USe input()for Python 3.x