pythonconditional-expressionsaugmented-assignment

Python one line if-else with different operators


I was fiddling with one line if and for statements in python and ran across the following problem:

I can make something like the following work:

state = 1 if state == 4 else 2

But I want to use = and += in the same context, something like this:

state = 1 if state == 4 else state+=1

How can I implement this in one line?


Solution

  • += is not an operator, it is a statement. You cannot use statements in an expression.

    Since state is an integer, just use +, which is an operator:

    state = 1 if state == 4 else state + 1
    

    The end result is exactly the same as having used an += in-place addition.

    Better still, use the % modulus operator:

    state = (state % 4) + 1
    

    which achieves what you wanted to achieve in the first place; limit state to a value between 1 and 4.