Articles

Program to find factorial of a number using recursion in Python

Program to find factorial of a number using recursion in Python


In this python programming guide, we are going to learn,

  • what is recursion?
  • program to find factorial of a number using recursion in python

What is recursion?

Recursion is when a function calls itself. In a recursion there is always a general function and a terminating condition. There results of all the function calls are returned to compute the final result.


Python program to find factorial of a number using recursion

The program to find factorial of a number using recursion in python is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

def fact(n):
    if n == 1 or n == 0:
        return 1
    else:
        return n * fact(n-1)

if __name__ == "__main__":
    n = int(input("Enter number: "))
    answer = fact(n)
    print("The factorial is:",answer)

The output of python program to find factorial of a number with recursion is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter number: 5
The factorial is: 120

Few important tips about this program

1. In the program we have introduced the concept of functions. Functions are just blocks of code which are used to give our code a modular approach and the logic and implementation can be kept separate. We define a function by def keyword.

2. In the function, the fact that if n is equal to zero or one will return one is the "Exiting condition". So long the exiting condition is not met, function will call itself.

3. The "__name__ == "__main__" " is just used to instantiate something like a main() method in C or Java. This is from where the main code begins to execute.

4. Finally, we store the answer and display it on the terminal.

 

Python program to find factorial of a number with recursion snapshot:

python program to find factorial of a number with recursion

 


Basic Python Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Data Science Enthusiast
Page Views :    Published Date : Feb 16,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!