0

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
4
  • This is python 2, isn't it? Commented Oct 21, 2018 at 10:10
  • 2
    Yeah, use Python 3. :) Commented Oct 21, 2018 at 10:11
  • it works for me? Commented Oct 21, 2018 at 10:11
  • @AlexisDrakopoulos 'Cause you're using python 3, where print is a function. Commented Oct 21, 2018 at 10:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.