How is this returning 8? I expect 6

Viewed 36
def power(num, x=1):
    result = 1
    for i in range(x): 
        result = result * num
    return result
print(power(num=2, x=3))

This is a Python function with a for loop in it that is supposed to print out the power of something but I am not sure how this code is working because the result is result * num.

Can someone please explain how this is returning 8 as answer, because if I multiply num with result, I get 6?

2 Answers

Welcome to SO! The power function revolves around the for-loop. Calling it with power(num=2, x=3) results in repeating the for-loop three times (from x).

First time: result = 1 * 2 ==> 2

Second time: result = 2 * 2 ==> 4

Third time: result = 4 * 2 ==> 8

By contrast, if you were expecting 6, try changing the statement in the for-loop to result = result + num. See?

See, power(num=2, x=3) are the parameters provided. def (num, x=1). It means if no value is given for x, then take it as 1.

def power(num, x=1):
    result = 1
    for i in range(x): 
        result = result * num
    return result
print(power(num=2, x=3))

In here, you are iterating over the value of x which is 3 in the case. Here is what it is doing. The range function returns all numbers in the specific range. So when range(x) means range(3) as x=3 and then it will iterate over it.

It is basically assigning the product of result and num which is 3. This is the output when you add print(result,num) inside the for loop.

1 2
2 2
4 2
8

In the first case, the value of result was 1. It was multiplied by 2 and reassigned to result like result=result*num. Therefore the new value of result is 2 x 1 = 2. Then again it is doing the same thing, taking the new value of result, multiplying by num and reassigning the value to result. This will continue until the loop ends.

So it will be:

1*2=2 #=== Reassigned to result
2*2=4 #=== Reassigned to result
4*2=8 #=== Reassigned to result

#=== End of loop ===

And at the last, when the loop ends, return result will return the value of result which is 8.

Related