How to Calculate Factorial in Python
Q: Write a python program to find the factorial of a number
- Python
- Senior level question
Explore all the latest Python interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Python interview for FREE!
Here's an example Python program to find the factorial of a number using a recursive function:
def factorial(n): # Base case: factorial of 0 and 1 is 1 if n == 0 or n == 1: return 1 # Recursive case: multiply n by factorial of (n-1) else: return n * factorial(n-1) # Test the function number = 5 print(f"The factorial of {number} is {factorial(number)}")
Output:
The factorial of 5 is 120
In this program, we define a function called factorial that takes an integer parameter n. The function uses recursion to calculate the factorial of n, which is defined as the product of all positive integers less than or equal to n. The base case of the recursion is when n is 0 or 1, in which case the function returns 1. Otherwise, the function multiplies n by the factorial of n-1 and returns the result.
We then test the function by calling it with the number 5 and printing the result. The output shows that the factorial of 5 is 120, which is the product of 5, 4, 3, 2, and 1.


