【发布时间】:2018-12-22 20:42:21
【问题描述】:
我们可以像这样使用 if-else:
statement if condition else statement
但是这里有一些问题,我不明白为什么。
-
如果我运行
count += 1 if True else l = [](计数已定义),则会引发错误:File "<ipython-input-5-d65dfb3e9f1c>", line 1 count += 1 if True else l = [] ^ SyntaxError: invalid syntaxelse 之后不能赋值吗?
-
当我运行
count += 1 if False else l.append(count+1)(注意:count = 0, l = [])时,会报错:TypeError Traceback (most recent call last) <ipython-input-38-84cb28b02a03> in <module>() ----> 1 count += 1 if False else l.append(count+1) TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'l 的结果是
[1]。
使用相同的条件,如果我使用 if-else 块,则没有错误。
你能解释一下区别吗?
【问题讨论】:
-
... if ... else ...不是简写/单行if ...: ... else: ...,而是完全不同的东西。 -
相关:Does Python have a ternary conditional operator?(接受的答案实际上解释了这个错误的原因)
-
x if y else z需要 表达式,并且您为其提供一个扩充的赋值 statement。您的基本误解是它采用statement if condition else statement的形式,而应该始终是<expression> if <expression> else <expression>
标签: python conditional-operator