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

Python if/elif语句异常:数值≥35时输出结果错误

Python代码问题排查与修复

问题原因

你代码里的条件判断用错了运算符:把逻辑与运算符and写成了位运算符&。Python中&的优先级高于比较运算符(>=、<=),导致35及以上数值的条件被错误解析,触发了不符合预期的分支。

举个例子,当tuk=35时,elif tuk >= 25 & tuk <=34会被解析为:

  1. 先计算位运算25 & 35,结果为1
  2. 再解析为链式比较tuk >= 1 <=34,即35 >=1 and 1 <=34,结果为True
  3. 因此会触发第二个分支,输出错误的结果

而tuk≤34时,位运算的结果刚好让链式比较符合你原本的预期,所以看似正常。

修正后的代码

tuk = 35  # 可替换为任意测试数值
if tuk <= 24:
    print('The text is very easy to read.')
elif tuk >= 25 and tuk <= 34:
    print('The text is easy to read.')    
elif tuk >= 35 and tuk <= 44:
    print('The text is moderately difficult to read.')
elif tuk >= 45 and tuk <= 54:
    print('The text is difficult to read')
elif tuk >= 55:
    print('The text is very difficult to read')
else:
    print('This is beyond')

验证说明

把所有&替换成and后,条件会按照你预期的逻辑执行:每个分支先判断数值范围的下限,再判断上限,35及以上数值会进入对应的正确分支。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:25:19