krypticbit
krypticbit

Reputation: 123

Python - Check if function returns value and capture it if so

At first, this question may seem rather stupid. But for some reason, I cannot figure it out for the life of me. I have some function, lets call it foo. foo will either return False or a unique string / number depending on what parameters are passed to it. I want to check if foo returns some value other then False, and if so process it. If it doesn't, I want to go on and do the same thing with a different parameter passed to foo. It can be done as below:

a = foo(1)
b = foo(2)
c = foo(3)
if a:
    print (a)
elif b:
    print (b + 3)
elif c:
    print ("abc" + c)

While this method works, it seems "clunky" to me. Is there any better way of doing this?

Upvotes: 0

Views: 5246

Answers (1)

John
John

Reputation: 6648

abc = [foo(i) for i in range(1,4)]
for x in abc:
    if x:
        print(x)
        break

or even

for x in [foo(i) for i in range(1,4)]:
    if x:
        print(x)
        break

Is this better than your method is subjective but I personally would prefer a reduced line count and a single collection over disparate variable names. The reason being their extensibility.

As regards the pseudo switch statement you have; no there is no better way although some may prefer to use dicts as LUT's. For example:

for i, x in enumerate(abc):
    if x:
        print([
            x,
            x+3,
            "abc"+x
        ][i])
        break

Upvotes: 1

Related Questions