Skip to content Skip to sidebar Skip to footer

Syntax Error In Ternary If-else Statement

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

Solution 1:

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 expressionsA or B and then return the result, whereas the latter will just execute either of the statementsA 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.

Solution 2:

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.

Solution 3:

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:

ifTrue:
    count += 1else:
    l = []

But what this line is really doing is something like:

ifTrue:
    count += 1else:
    count += l = []

Hence the syntax error.

Post a Comment for "Syntax Error In Ternary If-else Statement"