退出Python中的while循环

退出Python中的while循环,python,while-loop,Python,While Loop,以下是我有疑问的代码: 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() 我一直认为,当我输

以下是我有疑问的代码:

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循环来做同样的事情,但结果是一样的。我应该怎么做才能避免这个错误呢?

你可以这样做,这将打破
y
n

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

您可以这样做,这将打破
y
n

while isPet_list_elem not in ('y','n'):
这是德摩根定律

你可以说:

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

这是德摩根定律

你可以说:

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


你使用了错误的逻辑。当您在代码中输入
y
n
时,循环开头的条件显示为
True
,因此它将继续执行。将其更改为
语句,一旦输入
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
n
时,循环开头的条件显示为
True
,因此它将继续执行。将其更改为
语句,一旦输入
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”,则
isset\u list\u elem!=“n”
为真;如果输入“n”,则
isset\u list\u elem!=“y”
为真。在代码中使用
,因此,如果一个expressin为true,则整个语句都为true

您可以改为使用以下代码:

while isPet_list_elem != "y" and isPet_list_elem != "n"
如果输入“y”,则
isset\u list\u elem!=“n”
为真;如果输入“n”,则
isset\u list\u elem!=“y”
为真。在代码中使用
,因此,如果一个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

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

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

while
子句中的布尔运算符应该是
,而不是
。啊哈!我是否需要
为这两种情况返回True?如果
isPet\u list\u elem=“n”
isPet\u list\u elem!=“y”
为true,因此总表达式为true。如果
isPet\u list\u elem=“y”
isPet\u list\u elem!=“n”
为true,因此您的总表达式为true。所以在任何情况下,表达式都是真的。
while
子句中的布尔运算符应该是
,而不是
。啊哈!我是否需要
为这两种情况返回True?如果
isPet\u list\u elem=“n”
isPet\u list\u elem!=“y”
为true,因此总表达式为true。如果
isPet\u list\u elem=“y”
isPet\u list\u elem!=“n”
为true,因此您的总表达式为true。所以不管怎样,你的表达是正确的。对,我只是想了想,然后回到这里。对,我只是想了想,然后回到这里。但这个问题与德摩根定律无关。他在他的
while
循环中使用了错误的逻辑。这个问题与德·摩根定律有关。这就是原始代码不起作用的原因。是的,好的。但这个问题与德摩根定律无关。他在他的
while
循环中使用了错误的逻辑。这个问题与德·摩根定律有关。这就是为什么原始代码不起作用。