We can use if-else like this:
statement if condition else statement
但是这里还存在一些问题,我不明白为什么会出现这种情况。
If I run
count += 1 if True else l = []
(count is defined already), then it raises an error:File "<ipython-input-5-d65dfb3e9f1c>", line 1 count += 1 if True else l = [] ^ SyntaxError: invalid syntax
Can we not assign a value after else?
When I run
count += 1 if False else l.append(count+1)
(note: count = 0, l = []), an error will be raised: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'
and the result of l is
[1]
.
在相同的条件下,如果我使用 if-else 代码块,则不会出现错误。
你能解释一下其中的差异吗?
if ... else ...
不是缩写/单行写法的if ...: ... else: ...
,而是完全不同的东西。 - tobias_kx if y else z
is requires expressions, and you provide it an augmented assignment statement. Your fundamental misunderstanding is that it takes the formstatement if condition else statement
, rather it should always be<expression> if <expression> else <expression>
- juanpa.arrivillaga