Home > Net >  In Python is there any way to define the default value of a parameter to be based in other given par
In Python is there any way to define the default value of a parameter to be based in other given par

Time:10-11

I'm trying to do something like this:

def some_func(a, b = a):
    if not a:
        return b
    return a   b   some_func(a-1)

so, because it's called recursively, I can't get b inside the function, I want b to be the value of a at the first time the function is called. But I don't know how to do this because the way I tried it can't reach the value of a in the default assignment

CodePudding user response:

would something like this work?

a = 1
b = 2
def some_func(a, b):
    if not a:
        return b
    return a   b   some_func(a-1, b)
some_func(a, b)

CodePudding user response:

I've reached what I wanted doing

def some_func(a, b = None):
    if not b:
        b = a
    if not a:
        return b
    return a   b   some_func(a-1, b)

this way it only assigns b at the first time the function is called, like if some_func(7) is called, then b will be 7 until the end of the recursion, thanks for the comments y'all

  • Related