Why do some short form of conditionals work in python and some don't?
Let's take an example:
a = "foo" if True else "bar"
It's great and no problem. now take:
print("foo") if True else print("bar")
This raises an error.
I am assuming the former works as a ternary operator. Is there a way to write the second statement without resorting to full length:
if True:
print("foo")
else:
print("bar")
Something similar to Perl
print("foo") if True
source to share
-
All conditional expression paths must be evaluated.
-
In Python 2.7
print
, it is a statement , not a function. Thus, it cannot be evaluated as an expression.
Since the operator print
violates point 2, it cannot be used. But you can do
print "foo" if True else "bar"
In Python 3.x print
is a function , so you can write as you mentioned in the question
print("foo") if True else print("bar")
Since it print
is a function in Python 3.x, the result of the function call will be the result of evaluating the function call expression. You can check it like this
print(print("foo") if True else print("bar"))
# foo
# None
Function print
clearly returns nothing. So, by default, it returns None
. The result of the evaluation print("foo")
is None
.
source to share