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

Python中if复合条件语句逻辑不符合预期的问题咨询

问题原因与修复方案

你的代码逻辑不符合预期,核心问题是Python逻辑运算符的优先级:and的优先级高于or,所以你写的条件语句会被Python自动解析成:
(money >= 80 and hungry == True) or bored == True

这就导致两种情况都会触发print:

  • 要么money >=80且hungry为True
  • 要么不管money的值是多少,只要bored为True

完全偏离了你原本需要的「money >=80必须成立,同时hungry或bored至少一个为True」的逻辑。

修复方法

用括号强制改变运算顺序,把hungry和bored的判断部分括起来,让这部分先计算,再和money >=80做and运算:

money = 100
hungry = True
bored = True
if money >= 80 and (hungry == True or bored == True):
     print("You can buy something!")

另外,布尔变量本身可以直接作为条件,不需要和== True比较,简化后的代码更清晰:

money = 100
hungry = True
bored = True
if money >= 80 and (hungry or bored):
     print("You can buy something!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:20:58