用while循环python写factorial

时间:2016-02-17 20:42:05

标签: python loops while-loop factorial

我是新手,对Python不太了解。有人知道如何在while循环中编写阶乘法吗?

我可以在if / elif else语句中创建它:

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)

但我想用while循环(没有函数)来做这个。

7 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

如果您只想获得结果:math.factorial(x)

while loop:

def factorial(n):
    num = 1
    while n >= 1:
        num = num * n
        n = n - 1
    return num

答案 2 :(得分:0)

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

答案 3 :(得分:0)

使用标准库轻松实现:

import math

print(math.factorial(x))

答案 4 :(得分:0)

解决方案

number = 5 (choose a number you want to factorial) 
product = 1 (must start at 1) 
iteration = 1 (starting iteration that will increase +1) 
while iteration <= number:
    product = product*iteration
    iteration +=1
print(product)

幕后步骤:

产品= 1次迭代= 1 1 * 1 = 1

产品= 1次迭代= 2 1 * 2 = 2

product = 2次迭代= 3 2 * 3 = 6

product = 6次迭代= 4 6 * 4 = 24

product = 24次迭代= 5 24 * 5 = 120

答案 5 :(得分:-1)

string

答案 6 :(得分:-1)

我将使用while循环实现递归函数--- Factorial ----
(1)根据条件同时递归调用事实函数

def fact(num):
        while num>1:
            return num*fact(num-1)
        else:
            return num

    result = fact(3)
    print(result)

6