举个例子:
a = "foo" if True else "bar"
这执行得很好,没有问题。 现在采取:
print("foo") if True else print("bar")
这会引发错误。
我假设第一个像三元运算符一样工作。有没有一种方法可以在不求助于全长的情况下编写第二条语句:
if True:
print("foo")
else:
print("bar")
类似于 Perl 的东西
print("foo") if True
最佳答案
条件表达式的所有路径都必须是可计算的。
在 Python 2.7 中,
print
is a statement ,不是函数。因此,它不能作为表达式求值。
由于print
语句违反了第2点,所以不能使用。但你可以做到
print "foo" if True else "bar"
在 Python 3.x 中,print
is a function , 所以你可以按照你在问题中提到的那样写
print("foo") if True else print("bar")
由于 print
是 Python 3.x 中的函数,函数调用的结果将是函数调用表达式的求值结果。你可以这样检查
print(print("foo") if True else print("bar"))
# foo
# None
print
函数不会显式返回任何内容。因此,默认情况下,它返回 None
。 print("foo")
的计算结果是 None
。
关于python - 为什么一些简短形式的条件语句在 python 中起作用而有些则不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26397645/