[英]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")
您可以執行此操作,這將中斷y
或n
的循環
while isPet_list_elem not in ('y','n'):
您使用了錯誤的邏輯。 當您在代碼中輸入y
或n
時,循環開始處的條件顯示為True
因此它將繼續執行。 將其更改為and
語句,一旦輸入y
或n
,條件將為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.