Python Data Structures and Algorithms - Recursion: Factorial of a non-negative integer
4. Factorial Using Recursion
Write a Python program to get the factorial of a non-negative integer using recursion.
Sample Solution:
Python Code:
# Define a function named factorial that calculates the factorial of a given number 'n'
def factorial(n):
    # Check if 'n' is less than or equal to 1
    if n <= 1:
        # If 'n' is 1 or less, return 1 (base case for factorial)
        return 1
    else:
        # If 'n' is greater than 1, recursively call the factorial function
        # to calculate the factorial of (n - 1) and multiply the result by 'n'
        return n * factorial(n - 1)
# Print the result of calling the factorial function with the input value 5
print(factorial(5))
Sample Output:
120
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Python program to compute the factorial of a non-negative integer using a basic recursive approach.
 - Write a Python program to implement tail recursion for calculating factorial and compare its efficiency.
 - Write a Python program to calculate factorial recursively with error handling for negative inputs.
 - Write a Python program to recursively compute factorial and use it to solve a combinations problem (n choose k).
 
Go to:
Previous:  Write a Python  program  of recursion list sum.
  Next:  Write a Python program to solve the Fibonacci sequence using recursion.
Python Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
