Search code examples
pythonconditional-operator

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


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


Solution

  • 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