Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write factorial with while loop python

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).

like image 311
R overflow Avatar asked Feb 17 '16 20:02

R overflow


People also ask

Is there a factorial operator in Python?

factorial() in Python The factorial is always found for a positive integer by multiplying all the integers starting from 1 till the given number.


2 Answers

while num > 1:
    factorial = factorial * num
    num = num - 1
like image 144
John Gordon Avatar answered Nov 06 '22 19:11

John Gordon


If you just want to get a result: math.factorial(x)

While loop:

def factorial(n):
    num = 1
    while n >= 1:
        num = num * n
        n = n - 1
    return num
like image 28
leongold Avatar answered Nov 06 '22 20:11

leongold