The "conditional expression" A if C else B
is not a one-line version of the if/else statement if C: A; else: B
, but something entirely different. The first will evaluate the expressions A
or B
and then return the result, whereas the latter will just execute either of the statements A
or B
.
More clearly, count += 1 if True else l = []
is not (count += 1) if True else (l = [])
, but count += (1 if True else l = [])
, but l = []
is not an expression, hence the syntax error.
Likewise, count += 1 if False else l.append(count+1)
is not (count += 1) if False else (l.append(count+1))
but count += (1 if False else l.append(count+1))
. Syntactically, this is okay, but append
returns None
, which can not be added to count
, hence the TypeError.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…