2015-12-23 123 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