7 Python Recursion
1. What is Recursion?
Recursion means a function calls itself.
In simple words:
👉 A function does some work
👉 Then it calls itself again
👉 This continues until a stop condition is reached
2. Why Use Recursion?
Recursion is useful when:
-
A problem can be broken into small same problems
-
The solution repeats in a pattern
Examples:
-
Counting numbers
-
Factorial
-
Fibonacci series
3. Two Important Parts of Recursion
Every recursive function must have:
-
Base case – stops the recursion
-
Recursive call – function calls itself
Without base case ❌ → program runs forever.
4. Simple Recursion Example
Example: Print Numbers
5. How This Works (Step by Step)
-
0123456789101112print_numbers(5)Prints 5 → calls print_numbers(4)Prints 4 → calls print_numbers(3)Stops when n == 0
6. Recursion Example: Factorial
Factorial means:
Example
Output:
7. Recursion Example: Sum of Numbers
Example
8. Recursion Example: Fibonacci (Simple)
Example
9. When NOT to Use Recursion?
Avoid recursion when:
-
Loop is simpler
-
Performance matters
-
Very large values are used
Loops are often faster.
10. Common Beginner Mistakes
❌ No Base Case
❌ Infinite recursion.
❌ Wrong Base Condition
👉 Might never stop.
11. Recursion vs Loop (Simple)
| Recursion | Loop |
|---|---|
| Calls itself | Repeats with loop |
| Easy logic | Faster |
| Uses more memory | Uses less memory |
12. Simple Practice Examples
Example 1: Count Down
Example 2: Power of Number
Example 3: Reverse Print
13. Summary (Python Recursion)
✔ Function calls itself
✔ Base case is required
✔ Useful for repeated problems
✔ Be careful of infinite recursion
✔ Sometimes loop is better
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Modules
-
Exception Handling
-
File Handling
-
Mini Python Projects
Just tell me 😊
