情况
我本打算创造一款基于文本的冒险游戏,然后我遇到了这个问题,它似乎处于无限循环
def adventure():
print("You are in front of the gate of the tower. Will you Enter?")
ch = ""
while ch.lower() != "y" or ch.lower() != "n":
print("Please Choose")
ch = input("[Y] or [N]: ")
print(ch)
print("You are out of the while loop")
adventure()
我想让它使用户必须选择Y或N作为输入,但即使ch = Y或N程序仍然不能跳出while循环
示例输出
你在塔的门前。你会参加吗?
请选择
[Y] or [N]:
y
请选择
[Y] or [N]: N
n
请选择[Y]或[N]:
请选择[Y]或[N]:
为什么会发生这种情况,我如何解决这个问题?
这里的问题是您使用的是or
运算符而不是and
运算符
应该是:
print("You are in front of the gate of the tower. Will you Enter?")
ch = ""
while ch.lower() != "y" and ch.lower() != "n":
print("Please Choose")
ch = input("[Y] or [N]: ")
print(ch)
print("You are out of the while loop")
在设计while
循环时,有时更容易考虑使你退出循环的条件,然后直接否定它。
在您的示例中,当用户输入"y"
或"n"
时退出循环:
while not (ch.lower() == "y" or ch.lower() == "n"):
...
之后,您可以使用De Morgan定律简化条件:
第一步
while not ch.lower() == "y" and not ch.lower() == "n":
...
第二步
while ch.lower() != "y" and ch.lower() != "n":
...
有时python开发人员更喜欢使用not ==
而不是!=
,这取决于您的代码约定。