Fernando Crespo
Fernando Crespo

Reputation: 527

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

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

Upvotes: 6

Views: 4962

Answers (2)

mdml
mdml

Reputation: 22912

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

Upvotes: 10

NPE
NPE

Reputation: 500843

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.

Upvotes: 5

Related Questions