I am wondering if there is a more concise code on the below snippet.
def fun(x):
return x + 2
a = 3
x = fun(a)
m = x if x == 3 else 4
print(m)
Would this work?
def fun(x):
return x + 2
m = (x = fun(3)) if x == 3 else 4
print(m)
If you're determined to make it a one-liner, and for some reason you can only call fun once, you can use a lambda function:
m = (lambda x: x if x == 3 else 4)(fun(a))
You can see that this isn't terribly readable, and I wouldn't recommend it.
Your trial code wouldn't work because you can't do assignment in an expression.
It can be done, but it's not very readable/maintainable code:
m, = [ x if x == 3 else 4 for x in [fun(a)] ]
The assignment to x persists after it is used as the loop variable inside the list comprehension. Therefore, this one-liner has the effect of assigning both m and x in the way that you want.
for loops in ugly ways, I recommend the intellectual exercise of trying to get anything serious done in a Windows batch file.
fun(3)in the theoretical one-liner, you could usefun(3)inx = fun(3). Then, since you know3 == 3,m = 3 if fun(3) == 3 else 4. If this doesn’t work for your actual situation, please pick something representative of your actual situation.