Home > Enterprise >  Assign to variable inside one line if-else statement
Assign to variable inside one line if-else statement

Time:10-25

I want to assign to global variable in a one line if-else statement

The statement in one line:

wins  = 1 if num > num2 else lose  = 1;

I get invalid syntax error, with one line.

The original statement is working:

if num > num2:
    wins  = 1
else:
    lose  = 1  

I'm using more than 5000 statements, each one line and separate with semicolon ; to make it all one line.

CodePudding user response:

Assignments are statements, not expressions, and as such they cannot be part of a conditional expression. You can do it in one line, though, even if that is not an end in itself:

wins, lose = wins   (num > num2), lose   (num <= num2)

or with an assignment expression:

wins, lose = wins   (w := num > num2), lose   (not w)

CodePudding user response:

You can do it in one line as assignment expressions with the walrus (:=) operator (Python 3.8 ):

(wins := wins   1) if num > num2 else (lose := lose   1)

but it doesn't make much sense to. You're modifying two different objects, and trying to cram both into one statement isn't especially logical.

The 4-line version is perfectly reasonable.

  • Related