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:

  1. Base case – stops the recursion

  2. 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)


  •  

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

def power(a, b):
if b == 0:
return 1
return a * power(a, b - 1)

print(power(2, 3))

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 😊

You may also like...