原文: https://www.programiz.com/python-programming/examples/factorial

在本文中,您将学习查找数字的阶乘并显示它。

要理解此示例,您应该了解以下 Python 编程主题:


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

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

源代码

  1. # Python program to find the factorial of a number provided by the user.
  2. # change the value for a different result
  3. num = 7
  4. # To take input from the user
  5. #num = int(input("Enter a number: "))
  6. factorial = 1
  7. # check if the number is negative, positive or zero
  8. if num < 0:
  9. print("Sorry, factorial does not exist for negative numbers")
  10. elif num == 0:
  11. print("The factorial of 0 is 1")
  12. else:
  13. for i in range(1,num + 1):
  14. factorial = factorial*i
  15. print("The factorial of",num,"is",factorial)

输出

  1. The factorial of 7 is 5040

注意:要测试程序的其他编号,请更改num的值。

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