Besides the missing return
statement, note that your logic is also wrong. You are repeatedly squaring the number in each step, not mulitplying it with the original number. E.g., for pow(n, 3)
your code would calculate ((n²)²)² instead of n*(n*(n)). Also, in order to be a proper pow
function (assuming that is what you wanted to write), the num < 1
case should return 1
, not num
, so that pow(n, 3)
returns n*(n*(n*1)) and not n*(n*(n*n)).
def pow(num, num1):
if num1 < 1:
return 1
else:
return num * pow(num, num1 - 1)
This way, you pass the original value of num
to the recursive call, and not the squared value.
(Having said that, for any practical application you should of course use the builtin pow
function or the **
operator, just in case you did not know these.)
But why does the value not get returned from the if block? The value is getting updated n each of the recursive calls, if you execute and see the output.
You calculate the value and store it in the local variable num
, but that does not change the value of what was previously assigned to that name (numbers are immutable!). Thus you need return
to get it out of the function. See this example:
def test(num):
num = num * 2
print("inside", num)
return num
n = 5
r = test(n)
print("outside", n)
print("returned", r)