6

Why is that invalid

print('true') if False else print('false')

but this one is not

def p(t):
    print(t)

p('true') if False else p('false')
1
  • 4
    Because you're using Python 2 and print isn't a function in Python 2. Add from __future__ import print_function to the top of your file. Then it'll behave as you expect. Commented Mar 14, 2014 at 19:20

2 Answers 2

10

As has been pointed out (@NPE, @Blender, and others), in Python2.x print is a statement which is the source of your problem. However, you don't need the second print to use the ternary operator in your example:

>>> print 'true' if False else 'false'
false
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, in this case is true. But I generalized my use case. I should point that one "argument" it print and the other is a function. But I understand your point and it makes perfect sense!
5

In Python 2, print is a statement and therefore cannot be directly used in the ternary operator.

In Python 3, print is a function and therefore can be used in the ternary operator.

In both Python 2 and 3, you can wrap print (or any control statements etc) in a function, and then use that function in the ternary operator.

1 Comment

I know you understand this, but your answer is confusing. It's not that functions can be magically used in the ternary operator, it's that expressions can be used. Expression is an important vocabulary term that the OP should learn. And the OP is not trying to use a function in the ternary operator, but rather a function application. (yes, both are expressions, but the OP used only the 2nd)

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.