【发布时间】:2022-01-12 22:42:32
【问题描述】:
为了演示 python 执行短路,我尝试运行以下代码片段
True or print('here')
并期望代码执行,评估为True,而不是打印"here"。但是python 2.7报语法错误:
python2 -c "True or print('hier')"
File "<string>", line 1
True or print('hier')
^
SyntaxError: invalid syntax
Python3 的行为符合我的预期。 如果我将“打印”替换为另一个函数,Python2.7 也会按预期运行。
这是否是Python2.7中的一个bug,因为特殊语法的支持
print 'stuff'
或者这是预期的行为?当 print 语句作为第一个“条件”出现时,代码在 Python2.7 中也能正确执行。
Python 版本:Python 2.7.18
【问题讨论】:
-
print('here')不是 Python 2 中的表达式:它没有值,因此您不能将其用作操作数。 -
print是 Python 2.x 中的语句,而不是表达式,因此不能将其短路。
标签: python python-2.x short-circuiting