Logic behind Recursive functions in Python

Question:

I have the following recursive function below that returns the k to the s power of a certain integer.

However I do not understand how it works. The base class is 1 when s becomes 0.

How is it so that the returned value is actually k^s when 1 is returned? Since 1 is returned I would expect powertoK(k, s) to be 1 all the time.

Are there 2 memory addresses one holding 1 and the other as k^s?

def powertoK(k, s): 
    if s != 0:
        return k* powertoK(k,s-1)
    else:
        return 1
powertoK(3, 7) 
Asked By: Teoman Selcuk

||

Answers:

This is not related to memory addresses. Look at the different calls that happen during the recursion. I’m using smaller numbers () to keep it shorter:

powertok(2, 3)
= 2 * powertok(2, 2)
= 2 * 2 * powertok(2, 1)
= 2 * 2 * 2 * powertok(2, 0)
= 2 * 2 * 2 * 1
= 8

So only at the end the return value is 1 – but you are multiplying that with all the previous return values, because the initial call to powertok(2, 3) returns 2 multiplied by the return value of powertok(2, 2), and so on, until it gets multiplied by the return value of powertok(2, 0) which is the hardcoded 1 (instead of calling powertok again).

Answered By: ThiefMaster