Search code examples
pythonfunctionreturn

Can I use python return function to only return the value to the specific function


If I have this

def fun1:
    a = 2
    b = 3
    return a
    return b     #problem is here
def fun2:
    c = fun1()
print(fun1())

I want to return a be a default return and fun1 return a to every other functions but return b only works for returning to fun2 and nowhere else


Solution

  • What you can do is create an optional parameter for the function which decides what value to return.

    def fun1(arg=0):
        a = 2
        if arg != 0:
            a = 3
        return a
    def fun2():
        c = fun1(1)
    print(fun1())
    fun2()
    

    Here if you call fun1() without any arguments, it will return you 2. But if you give it any integer argument [ example: fun1(2) or fun1(1) ], it will return you 3.