【发布时间】:2017-04-27 12:59:09
【问题描述】:
我在这里的一个关于knapsack problems的问题中遇到了这个表达式:
def f(v, i, S):
if i >= len(v): return 1 if S == 0 else 0
count = f(v, i + 1, S)
count += f(v, i + 1, S - v[i])
return count
当我尝试以更一般的形式写出第二行 if i >= len(v): return 1 if S == 0 else 0 时,出现错误:
In [3]: if test1 : print x if test2 else print y
File "<ipython-input-3-9d4131fa0c48>", line 1
if test1 : print x if test2 else print y
^
SyntaxError: Missing parentheses in call to 'print'
这是一个通用的形式:
In [16]: if True : print("first") if True else print("second")
first
In [17]: if True : print("first") if False else print("second")
second
In [18]: if False : print("first") if True else print("second")
[nothing]
In [19]: if False : print("first") if False else print("second")
[nothing]
你怎么称呼它?
我很惊讶你可以取出 if...then...else 的第二个阳性案例并将其转换为 if...else。
更新:抱歉,python3 noob 的错误,我只是没有注意。如前所述,如果没有错误,答案就没有意义,所以我删除了错误的代码。
【问题讨论】:
-
称为条件表达式或三元表达式,见stackoverflow.com/questions/394809/…和docs.python.org/2/reference/…。
-
注意你的直接问题是
print()是 Python 3 中的一个函数,调用它需要括号。 -
在使用 Python 3 运行脚本时,您需要修复括号以进行打印。
-
我将问题回滚到您的原始帖子,因为您的编辑使接受和赞成的答案(您在打印声明中缺少
())毫无意义。 -
@SiHa,是的。我已经进行了必要的连续性校正。正确答案是示例。我知道条件表达式是什么。我想要的是单行的名称,如:“那么除了 if-if-else 之外,我还怎么称呼它?”哈哈。
标签: python if-statement