首页 > 编程知识 正文

Python 程序:计算一个数的阶乘

时间:2023-11-25 09:12:55 阅读:309050 作者:WUCQ

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

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

  • Python 函数
  • Python 数据类型
  • Python 决策语句

一个数的阶乘是多少?

在这个 python 程序中,我们必须使用 python 中的递归函数找到给定数字的阶乘。所以我们必须理解你所说的因子是什么意思。一个数的阶乘是从 1 到该数的所有数的乘积。

比如一个数5 的阶乘是 5 4 3 2 1 就是 120 。现在我们要明白什么是递归?递归是直接或间接重复调用自身的函数。在这里,我们必须递归调用阶乘函数,每次参数数小于 1。然后用一个小于 1 的参数乘以这个递归函数。

return num * factorial(num - 1)

python 中如何求一个数的阶乘?

在这个 python 程序中,我们接受来自用户的数字,并使用int数据类型将该数字保存在变量中。现在检查数字是否小于零。如果是这样,打印,我们不能做那个数字的阶乘。现在检查数字是否为零;如果是这样,那么打印该数字的阶乘为 1。否则我们调用函数阶乘(num) ,使用递归计算阶乘。在函数内部,我们使用 python 中的if条件来检查数字是否为 1。如果是,请返回数字。Else调用功能**return** num * factorial(num - 1).

算法

STEP 1: 使用 python 中的输入功能输入来自用户的数字。并将该字符串转换为整数并存储在变量中。

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

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

STEP 4: 调用阶乘函数,将数字作为参数传递。并将结果打印为数字的阶乘在 python 编程中定义用户函数阶乘

用户定义函数阶乘

步骤 1: 使用定义函数来定义带有参数的函数阶乘。

步骤 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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。