How to write factorial in python?

coldplay.xixi
Release: 2020-06-23 14:14:06
Original
11111 people have browsed it

How to write factorial in python?

How to write factorial in python?

How to write factorial in Python:

1. Calculation of factorial: Using a recursive function is a better solution. First define a recursive function to implement the calculation. factorial function.

def  recursion(n):   #'定义递归函数实现求阶乘功能'
    if n==1:
        return 1
    else:
        return  n*recursion(n-1)
Copy after login

2. Sum: (1) You can sum directly. You can also define a list, append the factorial results obtained by for traversal to the list, and then use the sum() function to sum.

Sum=0
print("for循环直接调用递归函数求和".center(80,"*"))
for  i  in range(1,21):
    Sum +=recursion(i)
print(Sum)
   
列表求和方案:
list=[] #定义一个空的列表,将调用递归函数生成的阶乘值追加到列表
print("将1-20的阶乘写入列表,使用sum函数求和".center(80,"*"))
for  i  in range(1,21):
    list.append(recursion(i))# 将调用递归函数生成的阶乘值追加到列表
print(sum(list)) #列表求和
Copy after login

[Complete source code] and results:

def  recursion(n): #'定义递归函数实现求阶乘功能'
    if n==1:
        return 1
    else:
        return  n*recursion(n-1)
 
 
list=[ ] #定义一个空的列表,将调用递归函数生成的阶乘值追加到列表
for  i  in range(1,21):
    list.append(recursion(i))# 将调用递归函数生成的阶乘值追加到列表
print(sum(list)) #列表求和
 
 
 
Sum = 0
for  i  in range(1,21):
    Sum +=recursion(i)
print(Sum)
 
 
结果:
2561327494111820313
Copy after login

Recommended tutorial: "python video tutorial"

The above is the detailed content of How to write factorial in python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template