Home > Blockchain >  Why am I getting a syntax error with this python ternary expression?
Why am I getting a syntax error with this python ternary expression?

Time:08-03

Why am I getting a syntax error with this python ternary expression? Can't find anything in the documentation to say this is bad

right_pointer -= 1 if condition else left_pointer = 1

CodePudding user response:

You are confusing statements and expressions. The conditional expression has the form

<true-expression> if <condition> else <false-expression>

but you are trying to use it like a statement consisting of two "substatements":

<true-statement> if <condition> else <false-statement>

That is, Python tries to parse this as

right_pointer -= (1 if condition else left_pointer  = 1)

not

(right_pointer -= 1) if condition else (left_pointer  = 1)

There is no one-line conditional statement; you should simply use the regular if statement:

if condition:
    right_pointer -= 1
else:
    left_pointer  = 1

The closest equivalent to what you are trying to write would be to use a conditional expression to select a bound method to call on 1, something like

(right_pointer.__iadd__ if condition else left_pointer.__isub__)(1)

Even this is not quite identical, as x = y is formally equivalent to x = x.__iadd__(y), not just x.__iadd__(y).

(Update: I forgot about the legal, though not recommended, use of :=. Don't actually use either of these.)

CodePudding user response:

This is not a good way to code, but if you want a one-liner:

(right_pointer := right_pointer - 1) if condition else (left_pointer := left_pointer   1)

This uses the walrus operator, which is in Python 3.8 .

But using a normal if/else is recommended:

if condition:
    right_pointer -= 1
else:
    left_pointer  = 1

As Chepner says in his answer, you can't use statements in the conditional expression, only expressions

  • Related