5

We can use if-else like this:

statement if condition else statement

but there are some problems here and I can't understand why.

  1. 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?

  2. 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?

3
  • 7
    ... if ... else ... is not a shorthand/one-line if ...: ... else: ..., but something entirely different. Commented Jul 14, 2018 at 19:10
  • Related: Does Python have a ternary conditional operator? (The accepted answer actually explains the reason for this error) Commented Jul 14, 2018 at 19:13
  • 1
    x if y else z is requires expressions, and you provide it an augmented assignment statement. Your fundamental misunderstanding is that it takes the form statement if condition else statement, rather it should always be <expression> if <expression> else <expression> Commented Jul 14, 2018 at 19:53

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

Comments

5

For your first error, you are trying to misuse a ternary expression. In Python, ternary expressions cannot contain statements they contain expressions.

As can be seen in Python's official grammar, an assignment is a statement, and a method call is an expression.

In your samples, l = [] is considered a statement, whereas l.append(...) is an expression.

For your second error, list.append returns None, not the list. Therefore, you are essentially trying to add None to either an integer, which is not permitted, hence the TypeError.

Lastly, please don't use the lowercase L's (l) or uppercase o's (O) as variable names. As stated in PEP 8, these can be extremely confusing variable names due to their similarity to 1's and 0's.

Comments

2

The one-line if-else statement in python is more like the ternary operator in other languages. It is not just a more compact version of an if-else block. The one-line if-else evaluates to a value, while the if-else block specifies conditions under which different actions should be taken. The single-line if-else statement is like a function that returns one value under some condition and another value if the condition is False.

So in your example, when you write count += 1 if True else l = [], what i think you mean is:

if True:
    count += 1
else:
    l = []

But what this line is really doing is something like:

if True:
    count += 1
else:
    count += l = []

Hence the syntax error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.