当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Custom non-recursive factorial function refuses further input after execution

问题描述:

I am trying to write a simple factorial function in Python, but upon execution, this one merely does nothing and inherently crashes the console for some bizarre reason.

Please bear in mind that I only began coding with Python about a week ago, and am used to using other lower level OOP languages, so please excuse any obvious mistakes.

Here is my current function:

# initialise factorial function:

def factorial(n):

i = 1 # initialise incrementing variable

while i < n:

n = n * i

i = i + 1

return n # return result

The function merely prints nothing and refuses any further input.

网友答案:

Try with this function: (works with n >= 0)

def factorial(n):
    r = 1
    i = 2
    while i <= n:
        # Use shorter version
        r *= i
        i += 1
    return r

Or (works with n > 0)

def factorial(n):
    i = n
    while i > 1:
        i -= 1
        n *= i
    return n
分享给朋友:
您可能感兴趣的文章:
随机阅读: