有人能告诉我一个很好的阶乘代码?

问题描述 投票:0回答:3

我刚开始学习Python的。我必须用Python3.7。有人能告诉我一个工作的阶乘代码?我试了一下,我发现在这里,但我总是得到这个错误:

=================== RESTART: C:\programozás\pytutorial.py ===================

码:

def factorial(n):

      result = 1

      for i in range(1, n + 1):

            result *= i

      return result
python python-3.x
3个回答
2
投票

您的代码工作,即使你可以简单地使用math库:

import math
print(math.factorial(5))

这个问题并非来自你的脚本,所以也许你应该试着重新安装蟒蛇,并避免与特殊字符的路径,亚当托斯指出。

更新:让输入和返回阶乘的问意见

import math
print(math.factorial(int(input(">>"))))

1
投票

问题是最有可能造成的,因为你必须在路径.py文件一个特殊字符。所以应该使用像C的文件夹:\程序,或没有任何特殊字符,如“A”。

做这样的这是非常重要的,即使它不解决当前的问题,它可以防止在未来更多。

PS:好点匈牙利程序员太:)


0
投票

我看到这个错误相关的(旧的)线程here

对于逻辑:我们必须考虑:

  1. 负数
  2. 正数

所以一个方式来写这将是:

def factorial(n):
 if n < 0:
    result = "Factorial doesn't exist for negative numbers"
 elif n == 0:
    result = 1
 else:
    result = 1
    for i in range(1, n + 1):
        result *= i
 return result

您可以尝试递归的概念也是如此。

为了得到一个数字“NUM”的阶乘:

print(factorial(num))

确保正确缩进代码缩进在Python重要。

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.