簡體   English   中英

為什么這個while循環不中斷?

[英]Why does this while loop not break?

如果輸入h,l或c,則此循環不會中斷:

x = input('enter h,l, or c')
while (x != 'c') or (x != 'h') or (x != 'l'):
    print('Sorry I didn't understand. Please enter h,l, or c')
    x = input("enter h,l, or c")

我想要的可以通過這種方式解決:

x = input("enter h,l, or c")
while True:
    if x == 'c' or x == 'h' or x == 'l':
        break
    else:
        print('Sorry I didnt understand. Please enter h,l, or c')
        x = input("enter h,l, or c")

第一段代碼有什么不正確的地方? X不會在一開始就被評估嗎?

看你的情況:

while (x != 'c') or (x != 'h') or (x != 'l'):

考慮輸入字符為c 第一個條件為False ,但其他兩個條件為True F或T或T為True

您需要and連接器處於您的狀況。 更好的是,嘗試

while not x in ['h', 'l', 'c']:

您應該使用and條件,而不是or 也就是說,如果它是可接受的字母之一,則將(x != 'c')(x != 'h')(x != 'h')評估為假。

x = input('enter h,l, or c')
while (x != 'c') and (x != 'h') and (x != 'l'):
    print("Sorry I didn't understand. Please enter h,l, or c")
    x = input("enter h,l, or c")

由於邏輯運算錯誤。

不是(A或B)

這個邏輯等於

(不是A)和(不是B)

所以第一個代碼應該是

x = input('enter h,l, or c')
while (x != 'c') and (x != 'h') and (x != 'l'):
    print("Sorry I didn't understand. Please enter h,l, or c")
    x = input("enter h,l, or c")

讓我們從聲明false or true評估為true的語句開始。 因此,如果xc(x != 'c')將為false ,但是第二種情況(x != 'h')將為true ,根據我們的第一個陳述,整個or表達式的計算結果為true,因此您的循環將永遠不會退出。 相反,您需要做的是:

x = input('enter h,l, or c')
while not ((x == 'c') or (x == 'h') or (x == 'l')):
    print("Sorry I didn't understand. Please enter h,l, or c")
    x = input("enter h,l, or c")

您的while循環將始終評估為True

0 x = input('enter h,l, or c')
1 while (x != 'c') or (x != 'h') or (x != 'l'):
2    print('Sorry I didn't understand. Please enter h,l, or c')
3    x = input("enter h,l, or c")

您的代碼已變成這樣:

0 x = input('enter h,l, or c')
1 while True:
2    print('Sorry I didn't understand. Please enter h,l, or c')
3    x = input("enter h,l, or c")

讓我們解釋一下。

輸入場景:

一種。 如果輸入為“ z”,則z不等於任何字母,因此在所有條件下均變為True 這意味着任何不是'h','l','c'之一的輸入都將求值為True

b。 如果輸入為“ h”,則h既不等於l也不等於c。 結果為True OR False OR True場景,並且顯然變為True 因此,如果您的輸入也是指定的任何字母,則它將是True因為它不等於條件中的其他字母,並且OR條件只需要一個True將條件求值為True

因此,您當前的代碼將始終評估為True,並且循環將無限運行。 您需要使用AND而不是OR ,使用發布的第二個代碼,或者可以使用遞歸。

推薦選項:

  1. 使用AND
x = input('enter h,l, or c')
while (x != 'c') and (x != 'h') and (x != 'l'):
    print("Sorry I didn't understand. Please enter h,l, or c")
    x = input("enter h,l, or c")

  1. 遞歸
def checker():
    x = input("enter h,l, or c")
    if (x != 'c') and (x != 'h') and (x != 'l'):
        print("Sorry I didn't understand. Please enter h,l, or c")
        checker()

checker()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM