首页 > 解决方案 > eval函数Python的错误输出

问题描述

你能解释一下为什么这个表达式的计算结果为 0 吗?

eval("(2==2|2==3)") # this is evaluated to 0 instead of 1

谢谢

标签: pythonscripting

解决方案


您使用了错误的运算符,因此您也得到了错误的优先级。

在 Python 中,or的优先级低于==, 而|具有更高的优先级。您的表达式被评估为2 == (2|2) == 3which is 2 == 2 == 3which is False

你想要2 == 2 or 2 == 3which 被评估为(2 == 2) or (2 == 3)which is True


推荐阅读