python

Is it possible to write a horizontal if statement with a multi-line body?


Is it possible to turn this:

if cond1 == 2 and cond2 == 3:
    a = 5
    b = 6
    c = 7

into something like this:

if cond1 == 1 and cond2 == 2: a = 5, b = 6, c = 7

Note: I know this is not readable, recommended or practical but for the task I have at hand this is what I would like to know and use.


Solution

  • Just change the commas to semicolons:

    if cond1 == 1 and cond2 == 2: a = 5; b = 6; c = 7
    

    Update: Some people mentioned using tuple assignment rather than semicolons, e.g. a, b, c = 5, 6, 7. It's true that this is probably more commonly seen, and will work in most cases, but it doesn't preserve the serial semantics of the original example. For instance, something like a = 5; b = a + 6; c = a + b won't work with tuple assignment, but will work with semicolons.