Python程序查找数字的阶乘


2022 年 3 月 30 日, 学习电子教程
1418

在这个简单的 Python 程序中,我们需要使用递归来查找数字的阶乘。这是一个关于递归函数的 Python 程序。

要理解这个例子,您应该了解以下 Python 编程主题

什么是数字的阶乘?

在这个 Python 程序中,我们必须使用 Python 中的递归函数来查找给定数字的阶乘。所以我们必须理解阶乘的含义。一个数字的阶乘是从 1 到该数字所有数字的乘积。

例如,数字 5 的阶乘是 5 * 4 * 3 * 2 * 1 = 120。现在我们必须理解什么是递归?递归是一个函数,它直接或间接重复调用自身。在这里,我们必须每次以小于 1 的参数递归调用阶乘函数。然后将该数字与以小于 1 的参数的递归函数相乘。

return num * factorial(num - 1) 

如何在 Python 中查找数字的阶乘?

在这个 Python 程序中,我们从用户那里获取数字,并使用 int 数据类型将该数字保存到一个变量中。现在检查数字是否小于零。如果小于零,则打印我们无法计算该数字的阶乘。现在检查数字是否为零;如果为零,则打印该数字的阶乘为 1。否则,我们调用函数 factorial(num) 来使用递归计算阶乘。在函数内部,我们使用 Python 中的 if 条件检查数字是否为 1。如果为 1,则返回该数字。Else 调用函数 return num * factorial(num - 1)。

算法

步骤 1:使用 Python 中的 input 函数从用户那里输入数字。并将该字符串转换为整数并存储在一个变量中。

步骤 2:使用 if 条件检查数字是否大于零。如果数字小于零,则打印无法找到负数的阶乘。

步骤 3:使用 elif 条件检查数字是否等于零。然后打印 的阶乘是 1

步骤 4:调用函数 factorial 并将数字作为参数传递。并打印结果作为数字的阶乘 在 Python 编程中定义用户函数 Factorial

用户定义的函数 factorial

步骤 1:使用 def 函数定义带参数的函数 factorial。

步骤 2:使用 if 条件检查数字是否等于 1。然后返回 num。

步骤 3:返回结果为数字乘以小于 1 的数字的阶乘函数。

Python 源代码

                                          def factorial(num):                         # recursive function that call itself to find the factorial of the number
     if num == 1:
        return num
    else:
        return num * factorial(num - 1)                    # finding factorial by multiplying number with factorial of that number less than one, 


num = int(input("Enter a Number to find the factorial: "))                 # accept a number in python using input function

if num < 0:

    print("Factorial for negative numbers cant be calculated")                    # check the number is negative or not and print cannot find factorial for negative numbers

elif num == 0:
    print("Factorial of 0 is 1")               # if the number is 0 then print factorial of number 0 is 1
else:
    print("Factorial of the number is: ", factorial(num))         # calling the factorial function using number as parameter
                                      

输出

Enter a Number to find the factorial: 5

Factorial of the number is: 120