Why won't this while loop have the same usage as the for loop to find factorial of a number in python?

Question:

I am new to programming and this code:

def factorial(n):
  number = 1
  result = 1
  for x in range(n):
    result *= number
    number += 1
  return result 

works fine to find a factorial of the number n.

However, once I change the code to:

def factorial(n):
  number = 1
  result = 1
  while number < n:
    result *= number
    number += 1
  return result 

it doesn’t work as intended when it looks to be the same piece of code (to me at least).

Can anyone enlighten why this ‘while’ loop does not work the same way as the ‘for’ loop? Thanks.

Asked By: user268493

||

Answers:

for x in range(n) iterates from 0 to n - 1.

while number < n iterates from 1 to n - 1, one less iteration.

If you change the while to while number - 1 < n both loops will be equal.

Answered By: Guy
Consider following examples
n = 5
number = 1
for x in range(n):
    print("foo")
    number += 1

outputs foo 5 times, whilst

n = 5
number = 1
while number < n:
    print("foo")
    number += 1

outputs foo 4 times. If you want to know more search for off-by-one error. That is reason why for is recommended for usage where you know number of runs a priori.

Answered By: Daweo

Lets see the difference in what happens:

In [6]: def factorial(n):
   ...:   number = 1
   ...:   result = 1
   ...:   for x in range(n):
   ...:     print(f"multiplying {result} by {number}")
   ...:     result *= number
   ...:     number += 1
   ...:   return result
   ...:

In [7]: factorial(5)
multiplying 1 by 1
multiplying 1 by 2
multiplying 2 by 3
multiplying 6 by 4
multiplying 24 by 5
Out[7]: 120

In [9]: def factorial(n):
   ...:   number = 1
   ...:   result = 1
   ...:   while number < n:
   ...:     print(f"multiplying {result} by {number}")
   ...:     result *= number
   ...:     number += 1
   ...:   return result
   ...:

In [10]: factorial(5)
multiplying 1 by 1
multiplying 1 by 2
multiplying 2 by 3
multiplying 6 by 4
Out[10]: 24

We can see that the second loop run 1 less time, this is because range(n) starts from 0, not from 1, so your loop had one more run

Answered By: Ron Serruya

While loop can be used as follows:

def factorial(number):
    answer = 1
    while number > 0:
        answer *= number
        number -= 1
    return answer
Answered By: nuru
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.