使用递归求数字阶乘的 Python 程序

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


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

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

源代码

# Factorial of a number using recursion

def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

num = 7

# check if the number is negative
if num < 0:
   print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   print("The factorial of", num, "is", recur_factorial(num))

输出

The factorial of 7 is 5040

注意:要查找其他数字的阶乘,请更改 num 的值。

在这里,数字存储在 num 中。该数字被传递给 recur_factorial() 函数以计算该数字的阶乘。


另请阅读

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

挑战

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

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

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

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

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