The expression method of factorial in python: first create a function with def code and create a variable res; then write a for range loop, perform calculations in the for loop and return res; finally use the print code to print the output factorial of 3.
The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.
How to express factorial in python:
1. Use def code to create a function with the name func and the parameters n
def func(n):
2. Create a variable res and assign it to the parameter n of the function. The code is as follows:
res = n
3. Then write a for range loop, specifically The code is as follows:
for i in range(1,n):
4. Next, the calculation is performed in the for loop and res is returned. The specific code is as follows:
res *= i return res
5. Use the print code to print out the factorial of 3. The code is as follows:
print(func(3))
6. The above code implements the factorial operation. In addition, we can also use recursion. way. The code is as follows:
def func1(n): if n==1: return 1 else: return n *func1(n-1) print(func1(3))
The recursive method is that the function calls itself
##Related free learning recommendations:
The above is the detailed content of How to express factorial in python. For more information, please follow other related articles on the PHP Chinese website!