Python 中的递归阶乘计算

PythonPythonBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("Raising Exceptions") subgraph Lab Skills python/comments -.-> lab-13628{{"Python 中的递归阶乘计算"}} python/conditional_statements -.-> lab-13628{{"Python 中的递归阶乘计算"}} python/function_definition -.-> lab-13628{{"Python 中的递归阶乘计算"}} python/raising_exceptions -.-> lab-13628{{"Python 中的递归阶乘计算"}} end

阶乘

编写一个函数 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 中处理异常。