Python中elif条件无语法错误却无法生效,请求技术帮助
问题分析与解决
你的问题出在逻辑运算符的使用错误上:Python中表示逻辑与的是and,而你用了&——这是按位与运算符,二者的优先级和功能完全不同,导致你的elif条件永远无法触发。
具体原因
&的优先级高于==,所以你的elif条件is_old == False & is_licenced == True会被Python解析为:
- 先计算
False & is_licenced(布尔值在按位运算中会被转为0/1,这里就是0 & 1,结果为False) - 再分别判断
is_old == False和False == True - 最终整个条件等价于
(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
相关产品推荐
相关产品推荐

