简体   繁体   English

为什么一些简短形式的条件在python中有效,有些则不然?

[英]why do some short form of conditionals work in python and some don't?

Take the example: 举个例子:

 a = "foo" if True else "bar"

This executes fine and without problems. 这执行得很好,没有问题。 now take: 现在采取:

print("foo") if True else print("bar")

This throws an error. 这会引发错误。

I assume the first one works like a ternary operator. 我假设第一个像三元运算符一样工作。 Is there a way to write the second statement without resorting to the full length: 有没有办法在不诉诸全长的情况下编写第二个语句:

if True:
    print("foo")
else:
    print("bar")

Something akin to Perl's 类似于Perl的东西

print("foo") if True
  1. All paths of a conditional expression , must be evaluatable. 条件表达式的所有路径都必须是可评估的。

  2. In Python 2.7, print is a statement , not a function. 在Python 2.7中, print是一个语句 ,而不是一个函数。 So, it cannot be evaluated as an expression. 因此,它不能作为表达式进行评估。

Since print statement violates point 2, it cannot be used. 由于print语句违反了第2点,因此无法使用。 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 在Python 3.x中, print是一个函数 ,因此您可以像在问题中提到的那样编写

print("foo") if True else print("bar")

Since print is a function in Python 3.x, the result of the function call will be the result of the evaluation of the function call expression. 由于print是Python 3.x中的函数,因此函数调用的结果将是函数调用表达式的评估结果。 You can check this like this 你可以这样检查一下

print(print("foo") if True else print("bar"))
# foo
# None

print function doesn't explicitly return anything. print函数没有显式返回任何内容。 So, by default, it returns None . 因此,默认情况下,它返回None The result of evaluating print("foo") is None . 评估print("foo")None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM