用于求数字阶乘的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


一个数的阶乘是所有从 1 到该数的整数的乘积。

例如,6 的阶乘是 1*2*3*4*5*6 = 720。负数的阶乘未定义,零的阶乘是一,0! = 1

使用循环计算一个数的阶乘

# Python program to find the factorial of a number provided by the user.

# change the value for a different result
num = 7

# To take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

输出

The factorial of 7 is 5040

注意:要测试不同数字的程序,请更改 num 的值。

这里,要计算阶乘的数字存储在 num 中,我们使用 if...elif...else 语句检查数字是负数、零还是正数。如果数字是正数,我们使用 for 循环和 range() 函数计算阶乘。

迭代 阶乘*i(返回值)
i = 1 1 * 1 = 1
i = 2 1 * 2 = 2
i = 3 2 * 3 = 6
i = 4 6 * 4 = 24
i = 5 24 * 5 = 120
i = 6 120 * 6 = 720
i = 7 720 * 7 = 5040

使用递归计算一个数的阶乘

# Python program to find the factorial of a number provided by the user
# using recursion

def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1 or x == 0:
        return 1
    else:
        # recursive call to the function
        return (x * factorial(x-1))


# change the value for a different result
num = 7

# to take input from the user
# num = int(input("Enter a number: "))

# call the factorial function
result = factorial(num)
print("The factorial of", num, "is", result)

在上面的示例中,factorial() 是一个递归函数,它会调用自身。这里,函数将通过递减 x 的值来递归调用自身。


另请阅读

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算一个数字的阶乘。

  • 非负整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。
  • 例如,对于输入 5,输出应为 120
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战