Home > Backend Development > Python Tutorial > How to express factorial in python

How to express factorial in python

coldplay.xixi
Release: 2023-01-03 09:28:04
Original
42117 people have browsed it

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):
Copy after login

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
Copy after login

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):
Copy after login

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
Copy after login

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))
Copy after login

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))
Copy after login

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!

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