原文: https://www.programiz.com/python-programming/examples/factorial
在本文中,您将学习查找数字的阶乘并显示它。
要理解此示例,您应该了解以下 Python 编程主题:
一个数字的阶乘是从 1 到该数字的所有整数的乘积。
例如,阶乘 6 是1*2*3*4*5*6 = 720。 没有为负数定义阶乘,零阶阶乘为 1,即0! = 1。
源代码
# Python program to find the factorial of a number provided by the user.# change the value for a different resultnum = 7# To take input from the user#num = int(input("Enter a number: "))factorial = 1# check if the number is negative, positive or zeroif num < 0:print("Sorry, factorial does not exist for negative numbers")elif num == 0:print("The factorial of 0 is 1")else:for i in range(1,num + 1):factorial = factorial*iprint("The factorial of",num,"is",factorial)
输出
The factorial of 7 is 5040
注意:要测试程序的其他编号,请更改num的值。
在这里,要查找其阶乘的数字存储在num中,我们使用if...elif...else语句检查该数字是负数,零数还是正数。 如果数字为正,则使用for循环和range()函数来计算阶乘。
