Write factorial with while loop python

2019-02-20 07:25发布

问题:

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

回答1:

while num > 1:
    factorial = factorial * num
    num = num - 1


回答2:

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


回答3:

number = int(input("Enter number:"))
factorial = 1
while number>0:
    factorial = factorial * number
    number = number - 1
print(factorial)


回答4:

Make it easy by using the standard library:

import math

print(math.factorial(x))


回答5:

a=int(input("enter the number : "))
result = 1
i=1
while(i <= a):
    result=i*result
    i=i+1
print("factorial of given number is ", format(result))