用 Python 程序求数的阶乘

2022-05-03 00:00:00 python 程序 阶乘

在本文中,您将了解如何通过Python计算数字的阶乘并显示它。
一个数的阶乘是从1到该数的所有整数的乘积。
例如,6的阶乘是1 * 2 * 3 * 4 * 5 * 6 = 720。阶乘不是为负数定义的,0的阶乘是1,0!= 1.
使用循环的方法计算阶层:

# 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)

输出:

The factorial of 7 is 5040

注意: 要测试不同数字的程序,请更改 num 的值。

在这里,要找到其阶乘的数字存储在 num 中,我们使用 if... elif... else 语句检查该数字是否为负、零或正。如果这个数是正数,我们使用循环和范围()函数来计算阶乘。

iteration 迭代 factorial*i (returned value) 阶乘 * i (返回值)

i = 1   1 * 1 = 1
i = 2   1 * 2 = 2
i = 3   2 * 3 = 6
i = 4   6 * 4 = 24
i = 5   24 * 5 = 120
i = 6   120 * 6 = 720
i = 7   720 * 7 = 5040

使用递归的方法求阶乘:

# Python program to find the factorial of a number provided by the user
# using recursion

def factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        # recursive call to the function
        return (x * factorial(x-1))


# change the value for a different result
num = 7

# to take input from the user
# num = int(input("Enter a number: "))

# call the factorial function
result = factorial(num)
print("The factorial of", num, "is", result)

在上面的示例中,factorial ()是一个调用自身的递归函数。在这里,函数将通过x递减递归调用自己。

相关文章