【问题标题】:Python 2 Syntax error when executing print in boolean expression在布尔表达式中执行打印时 Python 2 语法错误
【发布时间】: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


【解决方案1】:

在 Python 2 中,print 是一个语句。因此,它不能出现在需要表达式的二元运算符(如 or)的右侧。

如果您编写print('here') or True,它将被解析为 Python 2 中的语句 print ('here' or True)(将打印“此处”),而不是表达式 (print('here')) or (True)(其计算结果为 True 并打印“此处”为副作用),就像在 Python 3 中一样。

【讨论】:

  • 啊,这很有趣:)。感谢您也给print('') or True 发邮件。这种解释与(print('here')) or True 在 python2 中也引发 SyntaxError 的事实是一致的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多