Factorial Using Recursion
Calculate factorial through recursive multiplication in Python. Students trace zero factorial, a stopping condition, and pending products on the call stack.
1def factorial(n):2 # Base case3 if n == 0 or n == 1:4 return 156 # Recursive case7 return n * factorial(n - 1)89# Test10n = 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
Return one for n zero or one.
- 2
Request factorial of n - 1.
- 3
Multiply the returned result by n.
Walk through Factorial Using Recursion
factorial(4)
- 1.Calls for 4, 3, and 2 wait for the next smaller result.
- 2.factorial(1) returns the base value 1.
- 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.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum