Python while循环!=判断无法正常退出触发无限循环问题求助
问题触发原因
你代码中while循环的判断条件存在逻辑错误:
当前你写的条件是 ch.lower() != "y" or ch.lower() != "n",逻辑或(or)的规则是只要任意一个子条件成立,整体条件就为真:
- 当用户输入y时,
ch.lower() != "n"结果为真,整体条件成立,循环继续 - 当用户输入n时,
ch.lower() != "y"结果为真,整体条件成立,循环继续
无论用户输入任何内容,两个子条件必然有一个成立,因此循环永远不会退出。
修复方案
有两种常用的修复方式,任选其一即可:
方案1:修改逻辑运算符
将逻辑或(or)替换为逻辑与(and),修改后循环条件为:
while ch.lower() != "y" and ch.lower() != "n":
此时只有当输入既不是y也不是n的时候,循环条件才成立,会继续要求用户输入,符合你的需求。
方案2:使用成员判断(可读性更高)
直接判断输入的小写结果是否不在合法输入集合中,代码逻辑更直观:
while ch.lower() not in {"y", "n"}:
修改后完整可运行代码示例:
def adventure(): print("You are in front of the gate of the tower. Will you Enter?") ch = "" while ch.lower() not in {"y", "n"}: print("Please Choose") ch = input("[Y] or [N]: ") print(ch) print("You are out of the while loop") adventure()
内容的提问来源于stack exchange,提问作者ronron681
相关产品推荐
相关产品推荐

