-2

Like this,assume I need use some library function(I can not change them),it return a value or None, I want use the returned value and pass it to another function. How to avoid use many if statements at the same time?

Here is an example of my code:

import random
def somefunction1(n):
    m=random.randint(0,n)
    if m>5:
        return None
    else:
        return m

def somefunction2(n):
    # like somefunction1

# ------way one
r1=somefunction1(10)
r2=somefunction2(someParameter)
if r1:
    print(r1)
elif r2:
    print(r2)

# --------way two
r1=somefunction1(10)
if r1:
    print(r1)
else:
    r2=somefunction2(someparameter)
    if r2:
        print(r2)
2
  • Your question is not clear. What exactly is your question? Please check how to ask to learn how to write a good question. Commented Mar 15, 2020 at 12:18
  • I am not good at english,the description may be a bit vague.The code is pseudo-code. I search,find link this,but it can not use parameter. Commented Mar 15, 2020 at 12:34

3 Answers 3

1
if r := somefunction1(10) or somefunction2(someParameter):
    print(r)
Sign up to request clarification or add additional context in comments.

2 Comments

@krishna Woah, Python 8... welcome to the 21st, traveler :-)
Sorry, Python3.8 I mean to say.
0

Try this:

def a_function(parameters):
    default_value = None

    apply_some_operation_on(parameters):
        if YouWantToReturnSomething:
            default_value = whatever_you_want_to_return

    return return_val

Comments

0

Please check this, If you are not using out_put1 as input for another function then you can use like this.
If function1() return some value then out_put value will be that value.
else if function2() returns some value that then out_put will be value of function2() else it will be None

out_put =  function1() or function2()
if out_put:
    print(out_put)

1 Comment

Thank you, both this and this are good.

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.