Python Program to Find Factorial of Number Using Recursion
In this example, we will write a program that calculates factorial of a number using a recursive function in Python. To better understand this example, make sure you have knowledge of the following tutorials:-
Factorial of a number specifies a product of all integers from 1 to that number. It is defined by the symbol exclamation mark (!).
Python Program to Find Factorial of Number Using Recursion
def factorial(n): if n == 1: return n else: return n*factorial(n-1) num = int(input("Enter a number: ")) if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of", num, "is", factorial(num))
The output of the above program is:-
Enter a number: 5
The factorial of 5 is 120
The factorial of 5 is 120
Program Explanation:-
The calculation of factorial can be achieved using recursion in python. Here, a function factorial is defined which is a recursive function that takes a number as an argument and returns n if n is equal to 1 or returns n times factorial of n-1. A number is taken as an input from the user and its factorial is displayed in the console.