Search code examples
pythonpython-3.xfunctionrecursionparameters

In Python is there any way to define the default value of a parameter to be based in other given parameter?


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


Solution

  • I've reached what I wanted doing

    def some_func(a, b = None):
        if b is None:
            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