nelaaro
nelaaro

Reputation: 3236

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

Upvotes: 0

Views: 3429

Answers (2)

Alex
Alex

Reputation: 1418

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.

Upvotes: 1

Lefty
Lefty

Reputation: 405

The print function is a special statement in Python 2, so it can't be used in complex expressions line the ternary operator. Your code will work in Python 3.

Upvotes: 0

Related Questions