You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环判断输入字符串异常:匹配指定值仍无法终止循环

问题原因与解决方法

你的循环条件逻辑错误,导致合法输入也无法终止循环:
当使用or连接多个!=条件时,无论输入哪一个合法字符串,总有至少一个条件成立。比如输入str1时,example != 'str2'为True,整个or表达式结果就是True,循环会继续执行。

修正方案1:替换or为and

将循环条件中的or全部改成and,这样只有当输入同时不等于所有合法字符串时,才会进入循环:

example = input('enter string')
while example != 'str1' and example != 'str2' and example != 'str3' and example != 'str4':
    print('input str1, str2, str3 or str4')
    example = input('enter string')
# do stuff

修正方案2:使用not in简化判断

把合法字符串存入集合(或列表),直接判断输入是否不在合法集合中,代码更简洁易维护:

valid_strings = {'str1', 'str2', 'str3', 'str4'}
example = input('enter string')
while example not in valid_strings:
    print('input str1, str2, str3 or str4')
    example = input('enter string')
# do stuff

内容的提问来源于stack exchange,提问作者user20226026

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:35:40