简体   繁体   English

Python循环不断重复吗? 为什么?

[英]Python loop keeps repeating? Why?

Another_Mark = raw_input("would you like to enter another mark? (y/n)")

while Another_Mark.lower() != "n" or Another_Mark.lower() != "y":
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

if Another_Mark == "y":
    print "blah"

if Another_Mark == "n":
    print "Blue"

This is not the actual code I'm using except for the 1st three lines. 除了前三行之外,这不是我正在使用的实际代码。 anyways my question is why does the while loop keep repeating even when I input a value 'y' or 'n', when it asks again if you want to input another mark on the third line. 无论如何,我的问题是,即使我输入了值“ y”或“ n”,当再次询问是否要在第三行输入另一个标记时,为什么while循环仍会重复进行。 I'm stuck in a infinitely repeating loop. 我陷入了无限重复的循环中。 It shouldn't repeat when the value for Another_Mark is changed to either "y" or "n" 当Another_Mark的值更改为“ y”或“ n”时,不应重复

Try: 尝试:

while Another_Mark.lower() not in 'yn':
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

not in operator returns true if given object is not found in the given iterable and false otherwise. 如果在给定的可迭代对象中找不到给定的对象,则not in运算符将返回true,否则返回false。 So this is the solution you're looking for :) 所以这是您正在寻找的解决方案:)


This wasn't working due to boolean algebra error fundamentaly. 由于布尔代数错误从根本上讲,这没有用。 As Lattyware wrote: 正如Lattyware写道:

not (a or b) (what you describe) is not the same as not a or not b (what your code says) not(a或b)(您描述的内容)与not a或not b(您的代码所说的内容)不同

>>> for a, b in itertools.product([True, False], repeat=2):
...     print(a, b, not (a or b), not a or not b, sep="\t")
... 
True    True    False   False
True    False   False   True
False   True    False   True
False   False   True    True

Your loop logic only every comes out true - if the input is "n", then it's not "y" so it's true. 您的循环逻辑只有每一个都成立-如果输入为“ n”,那么它不是“ y”,因此成立。 Conversely if it's "y" it's not "n". 相反,如果它是“ y”,则不是“ n”。

Try this: 尝试这个:

while not (Another_Mark.lower() == "n" or Another_Mark.lower() == "y"):
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

Your logic behind the looping is wrong. 循环背后的逻辑是错误的。 This should work: 这应该工作:

while Another_Mark.lower() != "n" and Another_Mark.lower() != "y":
    Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")

You need to use AND instead of OR. 您需要使用AND而不是OR。

It's the way boolean logic distributes. 这就是布尔逻辑的分布方式。 You can say: 你可以说:

NOT ("yes" OR "no")

Or you can distribute the NOT into the parenthesis (which is what you're trying to do) by flipping the OR to an AND: 或者,您可以通过将OR翻转为AND,将NOT分配到括号中(这是您要尝试的操作):

(NOT "yes") AND (NOT "no")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM