Factorial Using Recursion
Calculate factorial recursively.
IntermediatePhase 3 - Level 1: Basic RecursionExample 2 of 10
factorial-using-recursion.py
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
What's going on
Factorial(n) = n * Factorial(n-1).
Key Concepts:
Base case: factorial(0) = factorial(1) = 1
Recursive case: n * factorial(n-1)
Function calls itself with n-1
🔗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