【问题标题】:why do some short form of conditionals work in python and some don't?为什么某些简短形式的条件在 python 中有效而有些则无效?
【发布时间】:2014-12-11 10:06:37
【问题描述】:

举个例子:

 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 python-2.7 conditional-statements


    【解决方案1】:
    1. 条件表达式的所有路径都必须是可计算的。

    2. 在 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

    【讨论】:

    • 我猜像continue 这样的东西被认为是陈述?这个想法是在continue if foo.startswith("#")这样的情况下不必写整个东西
    • @TitoCandelli:你可以在the documentation看到语句列表。
    • @TitoCandelli 是的,continuebreakpass 也是声明。语句可以执行,但不能求值。
    • 如有必要,可以在python 2.6 or laterfrom __future__ import print_function
    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 2020-02-23
    • 2021-05-28
    • 2021-09-17
    • 1970-01-01
    • 2022-06-21
    • 2015-12-21
    • 2019-12-27
    相关资源
    最近更新 更多