簡體   English   中英

在Python中退出while循環

[英]Exiting a while loop in Python

這是我有疑問的代碼:

isPet_list_elem = input("Pet?: ").lower()

# check if the input is either y or n
while isPet_list_elem != "y" or isPet_list_elem != "n":
    print("Please enter either 'y' or 'n'.")
    isPet_list_elem = input("Pet?: ").lower()

我一直認為,當我輸入“ y”或“ n”時,循環將結束,但是即使輸入y或n之后,循環仍繼續要求我輸入其他內容。

我嘗試使用其他while循環執行相同操作,但結果相同。 我應該怎么做才能避免這個錯誤?

這是德摩根定律。

你可以說:

while isPet_list_elem != "y" and isPet_list_elem != "n"

要么

while not (isPet_list_elem == "y" or isPet_list_elem == "n")

您可以執行此操作,這將中斷yn的循環

while isPet_list_elem not in ('y','n'):

您使用了錯誤的邏輯。 當您在代碼中輸入yn時,循環開始處的條件顯示為True因此它將繼續執行。 將其更改為and語句,一旦輸入yn ,條件將為False

isPet_list_elem = input("Pet?: ").lower()

# check if the input is either y or n
while isPet_list_elem != "y" and isPet_list_elem != "n":
    print("Please enter either 'y' or 'n'.")
    isPet_list_elem = input("Pet?: ").lower()

如果輸入“ y”,則isPet_list_elem != "n"為true; isPet_list_elem != "n"為true。 如果輸入“ n”,則isPet_list_elem != "y"為true。 並且您在代碼中使用or ,因此,如果一個expressin為true,則整個語句將為true。

您可以改用以下代碼:

while isPet_list_elem != "y" and isPet_list_elem != "n"

在while循環中包含以下內容:

    if isPet_list_elem == "y" or isPet_list_elem == "n":
            break

暫無
暫無

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

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