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

I can't understand how power outputs 1 in case the exponent x is zero (e.g., power(2, 0)).

In other words, how does the loop with range(0) works?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Bobrekci
  • 70
  • 1
  • 3
  • 2
    Welcome to Stack Overflow! Please read about [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). You can also use [Python-Tutor](http://www.pythontutor.com/visualize.html#mode=edit) which helps to visualize the execution of the code step-by-step. – Tomerikoo Dec 27 '20 at 11:14

2 Answers2

0

Let's first understand what range actually does. range, in its most basic version, takes a single integer as its parameter (in your case, x). It gives a list of integers (in Python 2) as the output (list in English is pretty much the same as list in python, but I'm not going into details here). The list contains numbers starting from 0 to the parameter, 0 included and the parameter excluded.

So, range(5) gives [0, 1, 2, 3, 4]

Now, your loop effectively becomes:

for i in [0, 1, 2, 3, ..., x]:

When x is 0, then the list can't include 0 either. So you get the following:

for i in []

Since there are no values i can take, the loop doesn't run!

Since you define result = 1 before the loop, return result simply spits out the same value if the loop isn't executed.

In Python 3, the range() function gives a generator object, similar to the xrange() function in Python 2.

Susmit Agrawal
  • 3,649
  • 2
  • 13
  • 29
0

for the input power(2,0) you are overriding the default value of x to 0.

now, inside a function, you have defined result = 1 as the initial value.

as you are moving in next instruction ie for i in range(x), and x=0 so this function will return an object with sequence start (inclusive) from 0 to end(exclusive) 0 with an increment (step) of 1, ie it create a empty result (list(range(0)) = [].

so as you iterate over it, it will exit the for loop and no operation on result variable will occur. so result keeps its the default value and you got 1 as return results when you call power(2,0).

sahasrara62
  • 10,069
  • 3
  • 29
  • 44