Home > Article > Backend Development > 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)
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)) #列表求和
[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
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!