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

Python中如何使用while语句实现多合法值的用户输入校验?

问题原因说明

你原代码的判断逻辑choice != ("go" or "asd")无法匹配"asd",是Python的or运算符特性导致的:所有非空字符串的布尔值都是True,a or b的规则是如果a为True直接返回a,否则返回b,所以("go" or "asd")实际的返回值只有"go",相当于你的判断条件等价于while choice != "go",自然只有输入go才会跳出循环。

最优实现方案

你可以把所有合法输入放到一个集合里,用not in做成员校验,这种写法可读性高,后续要新增合法输入只要往集合里加元素即可,不需要修改判断逻辑:

print("""
Instructions:
Use simple verb noun commands such as;
move book
go stairs
look vase
There are other hidden verbs and nouns. Try a few!
You might learn something no one else has!
"""
)

choice = ""
# 所有合法输入放在集合中,后续新增直接加元素即可
valid_inputs = {"go", "asd"}
while choice not in valid_inputs:
    choice = input("Type 'go' to the continue >")
return tombs()
    
instr()
扩展说明

如果你暂时不想用集合,也可以写多条件判断,但是合法输入越多写法越冗余,不如成员判断简洁:
while choice != "go" and choice != "asd":
注意这里要用and而不是or,因为你要判断的是「输入既不是go也不是asd的时候继续循环」。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:54:06