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')
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");
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.
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.
The ternary operator shorthand looks way more concise and shorter than a regular if/else statement.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With