Recursive Factorial Calculation with Python

  • Share this:

Code introduction


This function calculates the factorial of a non-negative integer, which is defined as n! = n * (n-1) * (n-2) * ... * 1. It uses recursion, where each recursive call decreases n by 1 and multiplies the current result by n.


Technology Stack : Recursion

Code Type : Recursive function

Code Difficulty : Intermediate


                
                    
def factorial(n, accumulator=1):
    if n < 0:
        return "Factorial is not defined for negative numbers."
    elif n == 0:
        return accumulator
    else:
        return factorial(n-1, n * accumulator)                
              
Tags: