用while循环python写阶乘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35467303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:28:54  来源:igfitidea点击:

Write factorial with while loop python

pythonloopswhile-loopfactorial

提问by R overflow

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

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

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

我可以在 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)

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

但我想用一个 while 循环(无功能)来做到这一点。

采纳答案by John Gordon

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

回答by leongold

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

如果你只是想得到一个结果:math.factorial(x)

While loop:

虽然循环:

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

回答by dinesh palem

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

回答by Max

Make it easy by using the standard library:

使用标准库使其变得容易:

import math

print(math.factorial(x))

回答by aravinda Challa

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

回答by Akash Rajpuria

I will implement the recursive function using while loop ---Factorial----
(1)It will call the fact function recursively based on while a condition

我将使用while循环实现递归函数---Factorial----
(1)它会根据while一个条件递归调用fact函数

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

    result = fact(3)
    print(result)

6

6