Why can't I use print in if ternary operator in python?

4.4k views Asked by At

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')
2

There are 2 answers

1
NPE On BEST ANSWER

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
mdml On

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