我正在学习python,我在以下代码中陷入无限循环。
A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
比较B时会发生问题,看它是否等于Y,y,N或n 但它仍然无论我为B提供什么输入都会让我进入while语句并让我留在那里。
答案 0 :(得分:2)
问题在于:
while B != "y" or B != "Y" or B != "N" or B != "n":
B
总是不等于其中之一。如果它" y"它不等于其他三个,依此类推。由于您使用or
来组合这些条件,如果任何一个为真,循环将继续,正如我们所见,情况总是如此。
使用and
重写:
while B != "y" and B != "Y" and B != "N" and B != "n":
或者应用DeMorgan的法律(将not
从表达式中移除并交换and
/ or
):
while not (B == "y" or B == "Y" or B == "N" or B == "n"):
或者最重要的是,用Python方式编写:
while B.lower() not in "yn":
(这也接受一个空答案,根据您的提示相当于" N"。要处理此问题,只需将您的elif
转换为普通else
,条件。)
答案 1 :(得分:1)
让我们使用while循环的简化版本。
while B != "Y" or B != "y":
# ...
这无法评估为False
。
如果B设置为Y
,则B != "Y"
将为False
,但B != "y"
为True
。
我认为,在这种情况下,做一些像
这样的事情可能会更干净while B not in ["y", "Y", "n", "N"]:
# ...
然后重复,直到输入是列表中的一个字符。
编辑:其他一些答案建议使用while B not in "yYnN"
或等价物。这可以在这里工作,因为您的所有预期响应都是一个字符。如果您稍后决定接受"yes"
作为回复,那么您将必须使用我上面显示的列表。
答案 2 :(得分:0)
问题在于您正在进行while B != "y" or B != "Y" or B != "N" or B != "n":
使用or
,如果其任一选项为true,则返回true。所以如果B =“N”
b!="N" or b!=n"
为真,因为b仍然不是“n”
您可以将所有or
替换为and
来解决此问题
while B != "y" and B != "Y" and B != "N" and B != "n":
答案 3 :(得分:0)
这一行
elif B == "N" or "n":
应该是
elif B == "N" or B == "n":
您应该使用条件,只需"n"
(非空字符串)表示true
答案 4 :(得分:0)
这是最简单的解决方案!
while B not in "YNyn":