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

Python中elif条件无语法错误却无法生效,请求技术帮助

问题分析与解决

你的问题出在逻辑运算符的使用错误上:Python中表示逻辑与的是and,而你用了&——这是按位与运算符,二者的优先级和功能完全不同,导致你的elif条件永远无法触发。

具体原因

&的优先级高于==,所以你的elif条件is_old == False & is_licenced == True会被Python解析为:

  1. 先计算False & is_licenced(布尔值在按位运算中会被转为0/1,这里就是0 & 1,结果为False)
  2. 再分别判断is_old == False和False == True
  3. 最终整个条件等价于(is_old == False) and (False == True),后者永远为False,所以elif分支永远不会执行

修正后的代码

把所有&替换为and即可:

is_old = False
is_licenced = True

if is_old == True and is_licenced == True:
    print('You are legally allowed to drive')
elif is_old == False and is_licenced == True:
    print("What'd you do, steal this from your parents??")
else:
    print("You can't drive.")

更简洁的写法

因为变量本身就是布尔值,没必要再和True/False比较,直接用变量本身或not取反更简洁:

is_old = False
is_licenced = True

if is_old and is_licenced:
    print('You are legally allowed to drive')
elif not is_old and is_licenced:
    print("What'd you do, steal this from your parents??")
else:
    print("You can't drive.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:12:47