Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Factorial Using Recursion

Calculate factorial through recursive multiplication in Python. Students trace zero factorial, a stopping condition, and pending products on the call stack.

IntermediatePhase 3 - Level 1: Basic RecursionExample 2 of 10
factorial-using-recursion.py
1def factorial(n):
2 # Base case
3 if n == 0 or n == 1:
4 return 1
5
6 # Recursive case
7 return n * factorial(n - 1)
8
9# Test
10n = int(input("Enter n: "))
11result = factorial(n)
12print(f"Factorial of {n} is {result}")

Output

Enter n: 5
Factorial of 5 is 120

In this one

  • Return a recursive product
  • Define zero factorial
  • Understand pending multiplication

How it works

  1. 1

    Return one for n zero or one.

  2. 2

    Request factorial of n - 1.

  3. 3

    Multiply the returned result by n.

Walk through Factorial Using Recursion

factorial(4)

  1. 1.Calls for 4, 3, and 2 wait for the next smaller result.
  2. 2.factorial(1) returns the base value 1.
  3. 3.Returns resolve to 2, then 6, then 24.

Edge cases

What is factorial(0)?

What is factorial(0)?

One, returned directly.

Why reject negative inputs?

Why reject negative inputs?

Subtracting one will never reach zero or one from a negative value.

What's going on

factorial(n) waits for factorial(n - 1), then multiplies its result by n. The base cases zero and one both return one.

For four, the pending products resolve as 2 * 1, 3 * 2, then 4 * 6. Python keeps those unfinished calls on its call stack. Negative values move away from both base cases; large depths also exceed the recursion limit.

What is factorial(0)? One, returned directly.

Why reject negative inputs? Subtracting one will never reach zero or one from a negative value.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does factorial(4) return?

Pick an answer to check it.

Question 2

What is factorial(0)?

Pick an answer to check it.

Questions people ask

What is factorial(0)?

One, returned directly.

Why reject negative inputs?

Subtracting one will never reach zero or one from a negative value.

What does factorial(4) return?

24.