We can use if-else like this:
statement if condition else statement
but there are some problems here and I can't understand why.
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 syntaxCan 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].
Using the same conditions, if I use an if-else block, there are no errors.
Can you explain the difference?
... if ... else ...is not a shorthand/one-lineif ...: ... else: ..., but something entirely different.x if y else zis 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>