Python 中的递归阶乘计算

Beginner

This tutorial is from open-source community. Access the source code

简介

在数学中,非负整数 n 的阶乘,用 n! 表示,是所有小于或等于 n 的正整数的乘积。例如,5! = 5 x 4 x 3 x 2 x 1 = 120。在这个挑战中,你将编写一个 Python 函数,使用递归计算给定数字的阶乘。

阶乘

编写一个函数 factorial(num),它接受一个非负整数 num 作为参数,并返回其阶乘。该函数应使用递归计算阶乘。如果 num 小于或等于 1,则返回 1。否则,返回 numnum - 1 的阶乘的乘积。如果 num 是负数或浮点数,该函数应抛出异常。

def factorial(num):
  if not ((num >= 0) and (num % 1 == 0)):
    raise Exception("Number can't be floating point or negative.")
  return 1 if num == 0 else num * factorial(num - 1)
factorial(6) ## 720

总结

在这个挑战中,你学习了如何使用递归计算一个数的阶乘。你还学习了如何在 Python 中处理异常。