-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)
gaofei
  • 31
  • 4
  • Your question is not clear. What exactly is your question? Please check [how to ask](https://stackoverflow.com/help/how-to-ask) to learn how to write a good question. – dspencer Mar 15 '20 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](https://stackoverflow.com/a/36117603/12583761) this,but it can not use parameter. – gaofei Mar 15 '20 at 12:34

3 Answers3

1
if r := somefunction1(10) or somefunction2(someParameter):
    print(r)
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
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)
krishna
  • 1,029
  • 6
  • 12
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
Harshit Jindal
  • 621
  • 8
  • 26