Search code examples
pythonprintingboolean-logicternary

Python use the print() function in a ternary conditional operator?


I don't understand why this fails

print('Yes') if True else print('No')
  File "<stdin>", line 1
    print('Yes') if True else print('No')
                                  ^
SyntaxError: invalid syntax

print('Yes') if True == False else print('No')
  File "<stdin>", line 1
    print('Yes') if True == False else print('No')
                                           ^
SyntaxError: invalid syntax

But this does work

print('Yes') if True else True
Yes

Solution

  • It's because in python 2, when you write:

    print('Yes') if True else True
    

    It actually is

    print(('Yes') if True else True)
    

    So you can write :

    print('Yes') if True else ('No')
    

    Or, a bit more beautifully

    print('Yes' if True else 'No')
    

    It means that you can only use ternary operations on the "argument" of print in python2.