美文网首页Python代码阅读
Python代码阅读(第75篇):阶乘

Python代码阅读(第75篇):阶乘

作者: FelixZzzz | 来源:发表于2021-11-09 18:03 被阅读0次

Python 代码阅读合集介绍:为什么不推荐Python初学者直接看项目源码

本篇阅读的代码实现了阶乘的计算功能。

本篇阅读的代码片段来自于30-seconds-of-python

factorial

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)

# EXAMPLES
print(factorial(6)) # 720

factorial函数接收一个数字,返回该数字的阶乘结果。

函数首先判断数字是否大于0,是否为整数(num % 1 == 0)。然后采用递归的方式进行求值,并给出递归终止条件(num == 0)。

相关文章

网友评论

    本文标题:Python代码阅读(第75篇):阶乘

    本文链接:https://www.haomeiwen.com/subject/gjwqzltx.html