Python Recursive Factorial Function Example
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This snippet defines a recursive Python function named factorial that calculates the factorial of a positive integer.
- The base case checks n == 1 and returns 1.
- Otherwise, the function calls itself with n-1 and multiplies the result by n.
- The statement print(factorial(6)) prints the factorial of 6, which is 720.
To use it, define the function and call it with a positive integer such as 5 or 6. Note that this implementation does not handle 0 or negative numbers properly and may cause a recursion error. A safer base case would be if n <= 1: return 1.