Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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')
like image 378
Fernando Crespo Avatar asked Mar 14 '14 19:03

Fernando Crespo


People also ask

Can we use printf in ternary operator?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");

Can ternary operator be used in if statement?

Yes you can. A ternary conditional operator is an expression with type inferred from the type of the final two arguments. And expressions can be used as the conditional in an if statement.

Can ternary operator be used in Python?

Practical Data Science using PythonMany programming languages support ternary operator, which basically define a conditional expression. Similarly the ternary operator in python is used to return a value based on the result of a binary condition.

Why use ternary operator instead of if-else?

The ternary operator shorthand looks way more concise and shorter than a regular if/else statement.


2 Answers

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
like image 195
mdml Avatar answered Oct 24 '22 00:10

mdml


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.

like image 26
NPE Avatar answered Oct 24 '22 01:10

NPE