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
相关产品推荐
相关产品推荐

