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.
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.