Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python 2 Syntax error when executing print in boolean expression

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading