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
AspectRecursionIteration
ApproachFunction calls itselfLoops (for, while)
MemoryUses stack O(n)More efficient O(1)
Best ForTrees, Graphs, BacktrackingSimple repetition
RiskStack overflowInfinite loops
ReadabilityCleaner for complex problemsSimpler 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.

ExceptionMeaning
ZeroDivisionErrorDividing by zero
ValueErrorInvalid value (e.g. int("abc"))
TypeErrorWrong data type
IndexErrorInvalid list index
KeyErrorInvalid dictionary key
FileNotFoundErrorFile does not exist
NameErrorVariable 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…