Python Functions & I/O
Functions, Recursion & Error Handling
Learn to write reusable code, handle errors gracefully, and work with files in Python.
Python 3
✓ Essential
4 Topics
Interview Key
01
Functions in Python
Python — Functions
# Default parameters def greet(name="Guest"): print("Hello", name) # *args — variable positional arguments def add_all(*args): return sum(args) # **kwargs — keyword variable arguments def student_info(**kwargs): for k, v in kwargs.items(): print(k, ":", v) # Lambda (one-line function) square = lambda x: x**2
print() vs return:
print() displays output but can't be reused. return sends value back to the caller. Always prefer return in DSA functions.02
Recursion in Python
Recursion — a function calls itself to solve a smaller version of the same problem. Every recursive function needs a Base Case and a Recursive Case.
Without a base case → infinite recursion → stack overflow error!
How Recursion Works (Step-by-Step)
For factorial(3):
Call Stack Visualization
factorial(3) = 3 * factorial(2)
= 3 * 2 * factorial(1)
= 3 * 2 * 1
= 6
# Stack grows then shrinks:
# Push: factorial(3) → factorial(2) → factorial(1)
# Pop: returns 1 → 2 → 6
Python — Recursion Examples
def factorial(n): if n == 1: return 1 # Base case return n * factorial(n - 1) # Recursive case def fibonacci(n): if n == 0: return 0 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) def sum_digits(n): if n == 0: return 0 return (n % 10) + sum_digits(n // 10) print(sum_digits(1234)) # 10
Recursion vs Iteration
| Aspect | Recursion | Iteration |
|---|---|---|
| Approach | Function calls itself | Loops (for, while) |
| Memory | Uses stack O(n) | More efficient O(1) |
| Best For | Trees, Graphs, Backtracking | Simple repetition |
| Risk | Stack overflow | Infinite loops |
| Readability | Cleaner for complex problems | Simpler for basic tasks |
Common Recursion Interview Questions
Interview Questions
# 1. What is recursion? A function calling itself to solve smaller subproblems. # 2. Key components? Base Case (stops) + Recursive Case (calls itself) # 3. What happens without base case? Stack Overflow Error (memory exhausted) # 4. Time complexity? Depends on number of recursive calls. Factorial: O(n), Fibonacci (naive): O(2ⁿ) # 5. What is tail recursion? Recursive call is LAST operation. Easier to optimize. Python does NOT optimize tail recursion. # 6. What is memoization? Caching results to avoid recomputation. Reduces Fibonacci from O(2ⁿ) to O(n). # 7. When to avoid recursion? - High memory usage risk - Stack overflow possible - Simple loop works better
Recursion is heavily used in: tree traversal, DFS, binary search, merge sort, quick sort, and backtracking.
Optimization Tip: Use Memoization to avoid repeated calculations. Essential for Fibonacci, climbing stairs, and other overlapping subproblem scenarios.
03
Exception Handling
Structure: try → except → else → finally. The finally block always runs — perfect for cleanup.
| Exception | Meaning |
|---|---|
ZeroDivisionError | Dividing by zero |
ValueError | Invalid value (e.g. int("abc")) |
TypeError | Wrong data type |
IndexError | Invalid list index |
KeyError | Invalid dictionary key |
FileNotFoundError | File does not exist |
NameError | Variable not defined |
04
File Handling in Python
Python — File Handling
with open("data.txt", "w") as file: file.write("Hello World\n") with open("data.txt", "r") as file: for line in file: print(line.strip()) # File existence check import os if os.path.exists("data.txt"): os.remove("data.txt")
Always use the
with statement — it automatically closes the file even on errors, preventing memory leaks.✓
Quick Quiz
1. *args collects…
2. **kwargs is a…
3. Closure keeps access to…
4. @decorator syntax wraps…
5. lambda best suited for…