在 Python 中退出一个 while 循环



这是我有疑问的代码:

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"为真;如果你输入"n",则isPet_list_elem != "y"为真。你在代码中使用or,所以,如果一个 expressin 是真的,整个语句就是真的。

您可以改用以下代码:

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

在 while 循环中包含以下内容:

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

最新更新