Reputation: 205
def power(num, x = 1):
result = 1
for i in range(x):
result = result * num
return result
So I came across a tutorial on calling functions with 2 arguments and this one in the picture was used as an example to show how you could make a function called power(num, x=1) that takes an interval in the first argument and raises it to the power of the second argument. Can someone explain in laymen's terms why this happens and what exactly is going on in this function and 'for' loop?
Upvotes: 0
Views: 678
Reputation: 1855
First, range(x)
is equivalent to range(0, x)
, and generates a sequence that ranges from 0
to x - 1
. For example, with range(3)
you get the sequence 0, 1, and 2, which has three elements. In general, range(x)
generates a sequence that has x
elements.
Second, for i in range(x)
makes i
iterates throught all the elements of range(x)
. Since range(x)
has x
elements, i
will iterate through x
different values, so the statements in the for
loop will be executed x
times.
With the above analysis, the body of the power
function is equivalent to the following:
result = 1
result = result * num
result = result * num
// repeat x times
result = result * num
which is equivalent to:
result = 1 * num * num * ... * num // x nums here
which, apparently, is num
raised to the power of x
.
Here's how this function works with specific input data. When num
is 3 and x
is 4, we have:
result = 1
result = result * num // = 1 * 3 = 3
result = result * num // = 3 * 3 = 9
reuslt = result * num // = 9 * 3 = 27
result = result * num // = 27 * 3 = 81 = 3^4
return result // 81 is returned
We can also show the execution process in more details:
result = 1
i = 0 // entering the loop
result = result * num // = 1 * 3 = 3
i = 1 // the second round of the loop begins
result = result * num // = 3 * 3 = 9
i = 2 // the third round of the loop begins
reuslt = result * num // = 9 * 3 = 27
i = 3 // the fourth and final round of the loop begins
result = result * num // = 27 * 3 = 81 = 3^4
// range(4) is exhausted, so the loop ends here
return result // 81 is returned
Upvotes: 2