Home  >  Article  >  Backend Development  >  How to express factorial in python

How to express factorial in python

coldplay.xixi
coldplay.xixiOriginal
2021-03-05 15:11:4742043browse

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.

How to express factorial in python

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

How to express factorial in python

2. Create a variable res and assign it to the parameter n of the function. The code is as follows:

res = n

How to express factorial in python

3. Then write a for range loop, specifically The code is as follows:

for i in range(1,n):

How to express factorial in python

4. Next, the calculation is performed in the for loop and res is returned. The specific code is as follows:

   res *= i
return res

How to express factorial in python

5. Use the print code to print out the factorial of 3. The code is as follows:

print(func(3))

How to express factorial in python

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

How to express factorial in python

##Related free learning recommendations:

python video tutorial

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!

Statement:
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