Is there a way to modify a variable twice in a one line if/else expression? it doesnt work with augmented assignement since this can not be destructured, so how could it be done if possible at all?
Desired functionality:
var = 2
if var > 1:
var += 1
var *= 3
Augmented assignement is obviously not working:
var = 2
var += 1 *=3 if var > 1 else var
or
var = 2
var += 1, *=3 if var > 1 else var
or
var = 2
var += 1, var *=3 if var > 1 else var
Joe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
7
There’s no way to do such a thing, because it simply isn’t intended to work !
As I pointed out in a comment, x if y else z
is an expression that is quite different from your standard, multi-line if-else : it returns a value, that value being x
if y
holds, else z
, x
, y
, and z
being expressions.
What you’re asking for is : can x
be something that modifies twice a variable.
And the answer is no, syntactically speaking ! x
can not even be something that modifies once a variable, since that would be a statement (roughly speaking, a block of code that does something and returns nothing, such as x += 3
or a for-loop) and not an expression (that (often) does nothing and returns something, such as 3
, "hi"
or even var + 3
).
The only way to do that is :
if cond:
var += 1
var *= 3
else:
pass
or maybe, to keep the one-liner style :
if cond: var = (var+1)*3; else: pass
But that’s pretty ugly.
To summarize : there’s statements that do things, expressions that return things, and mixing the two is not possible here.
1