0

I have a function that should return at least one output, and should return optional values depending on how I set the flag. For example:

def foo(a, b, f1=False, f2=False, f3=False):
    c = a + b
    if f1:
        d = a - b
    elif f2:
        e = a * b
    elif f3:
        f = a / b

    if f1:
        return c, d
    elif f2:
        return c, e
    elif f3:
        return c, f
    elif f1 and f2:
        return c, d, e
    elif f1 and f3:
        return c, d, f
    elif f2 and f3:
        return c, e, f
    elif f1 and f2 and f3:
        return c, d, e, f
    else:
        return c

If I have f1, f2, ..., fn as inputs, I will need to write 2**n return. That can be too many. Is there a better way to handle it? The example code is corrected according to @Tim Roberts' comments.

4
  • 1
    Return a list? Commented Apr 2, 2021 at 6:38
  • 2
    Do not write f1 & f2. This is not C. In Python, you write f1 and f2. The two are NOT interchangeable. Commented Apr 2, 2021 at 6:40
  • @Tim Roberts Thanks. Commented Apr 2, 2021 at 6:44
  • @Masklinn I still have to write many if statement to return different outputs Commented Apr 2, 2021 at 6:45

1 Answer 1

1

The way you have written it, you will never get multiple results. Only ONE of the if/elif/elif sequence will be used.

def foo(a, b, f1=False, f2=False, f3=False):
    answer = [a + b]
    if f1:
        answer.append( a - b )
    if f2:
        answer.append( a * b )
    if f3:
        answer.append( a / b )
    return answer
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.