Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
🔁 Recursion in Python: A Beginner-Friendly Guide
In programming, we often come across problems that require breaking them into smaller parts and solving them step by step. One powerful tool that allows us to do this elegantly is recursion. If you’re new to Python or programming in general, recursion may seem a bit tricky at first—but once you understand the logic, it opens doors to solving complex problems in a simplified way.
This guide will help you understand what recursion is, how it works in Python, and where and when to use it effectively—all in plain English with practical examples.
📌 What is Recursion?
Recursion is a programming concept where a function calls itself in order to solve a problem. It’s a method used to solve a problem by breaking it down into smaller and simpler sub-problems of the same type.
Think of recursion like a set of mirrors reflecting each other infinitely. The function continues to call itself until a base condition is met that stops the recursion.
🧠 Why is Recursion Important?
- ✅ Simplifies complex problems like tree traversal, factorial calculation, Fibonacci series, etc.
- ✅ Reduces code size for algorithms that naturally fit a recursive structure.
- ✅ Foundation for advanced topics like backtracking, divide-and-conquer algorithms, and dynamic programming.
🔍 Prerequisites
Before diving into recursion, you should be comfortable with:
- Python functions and how they work (
def
, calling functions, arguments) - Conditional statements like
if
,else
- Understanding return values in functions
🔑 Must-Know Concepts
1. Recursive Function
A recursive function is simply a function that calls itself.
def recursive():
# function logic
recursive()
But this alone is dangerous! It’ll lead to infinite recursion and crash your program unless we define a base case.
2. Base Case and Recursive Case
Every recursive function must have:
- A base case – to stop the recursion
- A recursive case – to keep calling itself
Example: Factorial Function
Factorial of a number (n!) = n × (n - 1) × … × 1
def factorial(n):
if n == 1: # base case
return 1
else: # recursive case
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
📘 Recursion in Action: Step-by-Step
Let’s trace factorial(3)
:
factorial(3)
→ returns3 * factorial(2)
factorial(2)
→ returns2 * factorial(1)
factorial(1)
→ returns1
(base case)
Now Python evaluates:
factorial(2)
→2 * 1 = 2
factorial(3)
→3 * 2 = 6
Final result: 6
✅ 5 Real Examples of Recursion in Python
1. Fibonacci Series
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(5)) # Output: 5
2. Sum of Natural Numbers
def sum_n(n):
if n == 0:
return 0
return n + sum_n(n-1)
print(sum_n(5)) # Output: 15
3. String Reversal
def reverse_string(s):
if len(s) == 0:
return s
return reverse_string(s[1:]) + s[0]
print(reverse_string("hello")) # Output: olleh
4. Palindrome Check
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome("radar")) # Output: True
5. Binary Search (Recursive)
def binary_search(arr, target, low, high):
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid+1, high)
else:
return binary_search(arr, target, low, mid-1)
arr = [1, 3, 5, 7, 9]
print(binary_search(arr, 5, 0, len(arr)-1)) # Output: 2
🔁 Recursion vs Iteration
Feature | Recursion | Iteration |
---|---|---|
Code style | Elegant and compact | More verbose |
Memory usage | High (due to function stack) | Low |
Speed | Slower (for deep recursions) | Faster |
Use case | Trees, graphs, factorials | Loops, repetitive tasks |
Risk | Stack overflow | Less error-prone |
⚠️ Common Mistakes to Avoid
- Missing base case → causes infinite recursion.
- Too large inputs → leads to maximum recursion depth exceeded.
- Returning wrong value → incorrect result.
- Using recursion where iteration is better.
🌍 Real-Life Applications
- Navigating file systems (folders inside folders)
- Solving puzzles like Sudoku or Maze
- Parsing mathematical expressions
- Processing tree and graph structures (e.g., DOM in HTML)
- Implementing algorithms like merge sort, quick sort
💡 Best Practices
- Always define a base case.
- Use recursion only when necessary.
- Consider tail recursion (although Python doesn’t optimize it).
- Limit recursion depth if needed (
sys.setrecursionlimit()
). - Prefer iteration when performance is a concern.
Recursion may seem magical at first, but at its heart, it’s just a function calling itself with new arguments—until a simple condition stops the process. With practice and real-world examples, you’ll see how recursion can simplify your code, especially for tasks involving repetition, nesting, or structure traversal.
As you continue learning Python, start experimenting with recursion. Write simple recursive functions and trace them step by step to understand how the flow works. Soon, recursion will be a natural tool in your programming toolkit!