Reputation: 3236
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
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
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