I know this might sound silly, but I want to know if there is a way like this to use.
My code is:
print(a (+=) if a==1 else (-=) b)
What I want it to do is,
if a==1:
print(a+b)
else:
print(a-b)
I know this might sound silly, but I want to know if there is a way like this to use.
My code is:
print(a (+=) if a==1 else (-=) b)
What I want it to do is,
if a==1:
print(a+b)
else:
print(a-b)
You can do this using the ternary condition operator:
a = a + b if a == 1 else a - b
If a == 1
is true, then a will hold the result of a + b
, else it will hold the result of a - b
Demo:
a = 4
b = 2
# a should equal to 2
a = a + b if a == 1 else a - b
a = 1
b = 2
# a should equal to 3
a = a + b if a == 1 else a - b
a = a+b if a==1 else a-b
is the sane and reasonable person's approach, so here's the less sane version that more directly selects the operation, not the complete expression including operands, removing the need to repeat the operands in two places:
from operator import iadd, isub # Like to += and -=, but you need to assign return
a = (iadd if a == 1 else isub)(a, b)
or even more concise/insane using bool
s to index a tuple
:
a = (isub, iadd)[a == 1](a, b)
To be clear, this is silly. Just use a = a+b if a==1 else a-b
.