企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Python 程序:查找数字阶乘 > 原文: [https://www.programiz.com/python-programming/examples/factorial](https://www.programiz.com/python-programming/examples/factorial) #### 在本文中,您将学习查找数字的阶乘并显示它。 要理解此示例,您应该了解以下 [Python 编程](/python-programming "Python tutorial")主题: * [Python `if...else`语句](/python-programming/if-elif-else) * [Python `for`循环](/python-programming/for-loop) * * * 一个数字的阶乘是从 1 到该数字的所有整数的乘积。 例如,阶乘 6 是`1*2*3*4*5*6 = 720`。 没有为负数定义阶乘,零阶阶乘为 1,即`0! = 1`。 ## 源代码 ```py # Python program to find the factorial of a number provided by the user. # change the value for a different result num = 7 # To take input from the user #num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if 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*i print("The factorial of",num,"is",factorial) ``` **输出** ```py The factorial of 7 is 5040 ``` **注意**:要测试程序的其他编号,请更改`num`的值。 在这里,要查找其阶乘的数字存储在`num`中,我们使用`if...elif...else`语句检查该数字是负数,零数还是正数。 如果数字为正,则使用`for`循环和`range()`函数来计算阶乘。