factorial函数
Python math.factorial()方法 (Python math.factorial() method)
math.factorial() method is a library method of math module, it is used to find the factorial of a given number, it accepts a positive integer number and returns the factorial of the number.
math.factorial()方法是数学模块的库方法,用于查找给定数字的阶乘,它接受正整数并返回数字的阶乘。
Note:
注意:
The method accepts only integer (positive) value, if the value is either a negative or float – it returns "ValueError".
该方法仅接受整数(正)值,如果该值是负数或浮点数,则返回“ ValueError” 。
If the number is 0 – its factorial will be 1.
如果数字为0 –其阶乘将为1。
Syntax of math.factorial() method:
math.factorial()方法的语法:
math.factorial(n)
Parameter(s): n – a positive integer number.
参数: n-正整数。
Return value: int – it returns factorial of given number n.
返回值: int –返回给定数字n的阶乘。
Example:
例:
Input:
a = 6
# function call
print(math.factorial(a))
Output:
720
Python代码演示math.factorial()方法的示例 (Python code to demonstrate example of math.factorial() method)
# Python code to demonstrate example of
# math.factorial() method
# importing math module
import math
# numbers
a = 0
b = 1
c = 6
d = 13
# printing factorial
print("factorial of ", a, " is = ", math.factorial(a))
print("factorial of ", b, " is = ", math.factorial(b))
print("factorial of ", c, " is = ", math.factorial(c))
print("factorial of ", d, " is = ", math.factorial(d))
Output
输出量
factorial of 0 is = 1
factorial of 1 is = 1
factorial of 6 is = 720
factorial of 13 is = 6227020800
ValueError: factorial() not defined for negative values
ValueError:factorial()未定义为负值
If we try to find the factorial of a negative integer value – method will return this error.
如果我们尝试找到负整数值的阶乘-方法将返回此错误。
# Python code to demonstrate example of
# math.factorial() method
# importing math module
import math
# -ve integer
a = -5
print(math.factorial(a))
Output
输出量
Traceback (most recent call last):
File "/home/main.py", line 10, in <module>
print(math.factorial(a))
ValueError: factorial() not defined for negative values
ValueError: factorial() only accepts integral values
ValueError:factorial()仅接受整数值
If we try to find the factorial of a float value – method will return this error.
如果我们尝试找到浮点值的阶乘-方法将返回此错误。
# Python code to demonstrate example of
# math.factorial() method
# importing math module
import math
# -ve integer
a = 5.1
print(math.factorial(a))
Output
输出量
Traceback (most recent call last):
File "/home/main.py", line 10, in <module>
print(math.factorial(a))
ValueError: factorial() only accepts integral values
Recommended posts
推荐的帖子
翻译自: https://www.includehelp.com/python/math-factorial-method-with-example.aspx
factorial函数