[英]Assign to variable inside one line if-else statement
I want to assign to global variable in a one line if-else
statement我想在一行
if-else
语句中分配给全局变量
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 ;
我使用了 5000 多个语句,每一行并用分号分隔
;
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+):您可以在一行中使用 walrus (
:=
) 运算符(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. 4行版本是完全合理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.