Factorial of a Number using Recursion in Python

Problem: Write a python program to find factorial of a number using recursion.

Solution: This python program accepts a number from user, passes it to a function named factorial_using_recursion() which checks whether given number is equal to 1, if yes then the Factorial of given number is 1 and program stops else this function calls itself with number - 1 as parameter to the function. Like wise this process continues until given number passed to the function is 1 and finally factorial of given number is returned to the calling function i.e. main() function.

To understand the concept of recursion better please read Recursion in C.

Factorial of a number in python

Here is the source code to find factorial using recursion in python
  1. def factorial_using_recursion(num):
  2. if num == 1:
  3. return num
  4. else:
  5. return num*factorial_using_recursion(num-1)
  6. number = int(input("Enter any number: "))
  7. if number < 0:
  8. print("Negative numbers dont have factorial")
  9. elif number == 0:
  10. print("Factorial of 0 is 1")
  11. else:
  12. print("The factorial of", number, "is", factorial_using_recursion(number))


Enter any number: 5
The factorial of 5 is 120