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

Python中or运算符误用导致分支逻辑异常问题咨询

问题分析与解决:or运算符的误用

你确实误用了or运算符,问题出在条件表达式的逻辑上:

  • 你写的if inp == "s" or "stand",Python会把它拆成两个独立判断:inp == "s" 和 "stand"。
  • 非空字符串在布尔判断中永远为True,所以不管inp是什么值,整个条件都会成立,自然每次都进入第一个分支。

正确的写法有两种:

  1. 完整写出每个相等判断:
if inp == "s" or inp == "stand":
    print("stand")
elif inp == "h" or inp == "hit":
    print("hit")
else:
    # 其他输入的处理
    pass
  1. 用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_

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:04:53