Pradeep Kumar
Pradeep Kumar

Reputation: 143

Return value if the value is true in python

I want to the return the value of the statement if it evaluates to true. For example,

if f():
   return f()
elif g():
   return g()

The function may return a list also. since empty list evaluates to false, is there a better way to do it. I don't want to store the value outside the scope of the if statement.

Upvotes: 0

Views: 512

Answers (1)

javidcf
javidcf

Reputation: 59681

Currently you can only do:

out = f()
if out: return out
out = g()
if out: return out

But maybe what you are thinking of is something like the (controversial) assignment expressions coming up in Python 3.8. With this you will be able to do:

if out := f():
    return out
elif out := g():
    return out

Upvotes: 3

Related Questions