Syntax error in if else statement

  • A+
Category:Languages

we can use if-else like this: statement if condition else statement,but there are some problems here I can't understand why?

  1. if i run count += 1 if True else l = [](count is defined already), then raise a error:

    File "<ipython-input-5-d65dfb3e9f1c>", line 1 count += 1 if True else l = []                           ^ SyntaxError: invalid syntax 

Can not it be assigned value after else?

  1. when run count += 1 if False else l.append(count+1)(note: count = 0, l = []), there is a error will be raise:

    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].

As same condition, if I use if-else block,there are no error. Can you explain it the difference.

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: