In order to demonstrate that python performs short-circuiting I tried to run the following code snipplet
True or print('here')
and expected the code to execute, evaluate to True
and not print "here"
. However, python 2.7 reports a syntax error:
python2 -c "True or print('hier')"
File "<string>", line 1
True or print('hier')
^
SyntaxError: invalid syntax
Python3 behaves as I would have expected. If I replace "print" with another function Python2.7 also behaves as expected.
Is this a bug in Python2.7 because of the support of the special syntax
print 'stuff'
or is this intended behavior? When the print statement comes as the first "condition", the code executes correctly in Python2.7 aswell.
Python version: Python 2.7.18
CodePudding user response:
In Python 2, print
is a statement. As such it cannot appear on the right hand side of a binary operator like or
where an expression is expected.
If you write print('here') or True
it is parsed as the statement print ('here' or True)
in Python 2 (which will print 'here'), not as the expression (print('here')) or (True)
(which evaluates to True
and prints 'here' as a side effect) as in Python 3.