Python 计算某个数的阶乘的程序

以下各节展示了计算阶乘的四种方法 Python — for 循环、if-else 版本、递归和 math.factorial() — 以及底层算法和应用。
使用 for 循环计算数字的阶乘
让我们以……为例。 Python 这段代码接受一个正整数作为输入,计算正整数的阶乘。在下面的代码中,循环从 1 开始,然后依次乘以待计算阶乘的整数前面的每个数字。
下列 Python 这段代码使用循环演示了阶乘函数。
Python 码:
print ("Input a number") factorialIP = int (input ()) ffactor23 = 1 for j in range (1, factorialIP+1): ffactor23 = ffactor23 * j print ("The factorial of the number is “, ffactor23)
输出:
Input a number
4
The factorial of the number is 24
以上 Python 该程序只接受正数输入,不检查负数。在这个程序中,当 j 等于 1 时,因子为 1。当 j 等于 2 时,因子乘以 2,如此循环,直到 j 等于 4,最终得到 24。
使用 IF…else 语句计算数字的阶乘
下列 Python 这段代码使用函数演示了阶乘函数。与循环版本不同的是,该程序在计算阶乘之前还会检查是否为负数。
在前 Python 代码中没有应用对负数的检查,导致阶乘函数不完整,如果输入负数,则容易出现错误信息。
在给定的代码中,循环从 1 开始,并乘以前面的每个数字,并且该函数还会验证输入是否为负数。
Python 码:
print("Enter a number for the purpose of determining factorial") factorialIP = int(input()) def factorial(factorialIP): if factorialIP < 0: print ('Factorial does not exist') factor=0 return factor elif factorialIP == 0: factor=1 return factor print(factor) else: factor = 1 for j in range (1, factorialIP+1): factor = factor * j return factor print ("The factorial of the number is ", factorial(factorialIP))
输出:
1) Enter a number to determine factorial -4 Factorial does not exist The factorial of the number is 0 2) Enter a number to determine factorial 4 Factorial does not exist The factorial of the number is 24
本篇 Python 该程序接受正数,并使用 if 和 else 语句检查负数,对于输入的 4 正确地返回 24。
使用递归计算数字的阶乘
下列 Python 这段代码演示了如何使用递归实现阶乘函数。在这个例子中,一个递归函数接受一个正整数作为输入,并计算其阶乘。
Python 码:
print("Enter a number for the purpose of determining factorial") def factorial(num2): if num2 < 0: return 'Factorial does not exist' elif num2 == 0: return 1 else: return num2 * factorial(num2-1) number1 = int(input()) print("The factorial of the number is",factorial(number1))
输出:
Enter a number for the purpose of determining factorial 4 The factorial of the number is 24
递归可以解释为这样一种概念:在递归中调用的函数…… Python 模块可以反复调用自身。它会一直运行,直到…… Python 模块中存在的条件得到满足,其中调用的函数被传递了一个值。
在上面 Python 程序中,函数 def factorial 会不断递归调用自身,直到数字变为零。一旦数字变为零,它就将数字初始化为 1,递归结束。
使用 math.factorial() 计算一个数的阶乘
下列 Python 代码演示了使用 math.factorial() 的阶乘函数,可以通过导入 math 模块来使用它。
此函数不接受负整数,如果提供的是浮点数,则会抛出值错误。
Python 码:
print("Enter a number for computing factorial") import math number1 = int(input()) print("The factorial is as computed comes out to be ") print(math.factorial(number1))
输出:
Enter a number for computing factorial 4 The factorial, as computed, comes out to be 24
阶乘程序的算法 Python
让我们举一个例子来说明阶乘的概念。
要计算 5 的阶乘,请按以下步骤操作:
5! = 5 x (5-1) x (5-2) x (5-3) x (5-4) 5! =120
这里,5!表示为120。
下图有助于理解计算阶乘的算法,在本例中,让我们以阶乘 4 为例!
阶乘 4 的算法兼图形示例!
阶乘在 Python
数的阶乘在数学中有广泛的应用。以下是阶乘的重要应用 Python:
- Python 有助于进行计算,并以比其他可用编程语言更快、更高效的方式打印阶乘。
- 此 Python 代码易于理解,并且可以在不同平台上复制,并且阶乘 Python 该程序可以应用于多个数学模型构建任务中。

