Python中or运算符误用导致分支逻辑异常问题咨询
问题分析与解决:or运算符的误用
你确实误用了or运算符,问题出在条件表达式的逻辑上:
- 你写的
if inp == "s" or "stand",Python会把它拆成两个独立判断:inp == "s"和"stand"。 - 非空字符串在布尔判断中永远为
True,所以不管inp是什么值,整个条件都会成立,自然每次都进入第一个分支。
正确的写法有两种:
- 完整写出每个相等判断:
if inp == "s" or inp == "stand": print("stand") elif inp == "h" or inp == "hit": print("hit") else: # 其他输入的处理 pass
- 用
in运算符简化判断(更推荐):
if inp in ["s", "stand"]: print("stand") elif inp in ["h", "hit"]: print("hit") else: # 其他输入的处理 pass
这样就能实现输入s或stand走第一个分支,h或hit走第二个分支,其他输入走else分支的需求。
内容的提问来源于stack exchange,提问作者Medak_
相关产品推荐
相关产品推荐

