Write factorial with while loop python

R overflow picture R overflow · Feb 17, 2016 · Viewed 47.9k times · Source

I am new and do not know a lot about Python. Does anybody know how you can write a factorial in a while loop?

I can make it in an if / elif else statement:

num = ...
factorial = 1

if num < 0:
   print("must be positive")
elif num == 0:
   print("factorial = 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print(num, factorial)

But I want to do this with a while loop (no function).

Answer

John Gordon picture John Gordon · Feb 17, 2016
while num > 1:
    factorial = factorial * num
    num = num - 1