Python: Iteration to Exceptions
Control, Abstraction, and Robustness. Iterate with intention, package behaviour in functions, generate lazily, wrap carefully, know where your names live, and let errors speak in the language of your problem.
1. Iterate with for
A for loop in Python is not a counter. It is an iterator protocol. It asks an object: "Give me your next item," until there is none left.
fruits = ["apple", "mango", "banana"]
for fruit in fruits:
print(fruit)
Internally: iter(fruits) → repeatedly next(iterator) → StopIteration ends the loop.
marks = {"Anitha": 92, "Kumar": 78, "Priya": 85}
for name, mark in marks.items():
print(f"{name} scored {mark}")
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)
for i in range(len(list)), stop. Use for item in list or for i, item in enumerate(list).2. Comprehensions
A comprehension is a for loop compressed into an expression that builds a new collection.
numbers = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in numbers]
even_squares = [n * n for n in numbers if n % 2 == 0]
name_lengths = {fruit: len(fruit) for fruit in fruits}
first_letters = {fruit[0] for fruit in fruits}
Structure: [expression for variable in iterable if condition]
[print(x) for x in numbers] is bad style. Use a normal loop for actions, comprehension for building values.3. Functions
def greet(name, greeting="Vanakkam"):
"""Return a greeting message."""
return f"{greeting}, {name}!"
print(greet("Anitha"))
print(greet("Kumar", greeting="Hello"))
def total(*numbers):
return sum(numbers)
def show_profile(**details):
for key, value in details.items():
print(key, ":", value)
def min_max(data):
return min(data), max(data)
low, high = min_max([10, 20, 5, 30])
Parameters are in the definition. Arguments are in the call. Never use a mutable default like def f(x=[]).
4. Generators
A normal function computes everything at once. A generator computes one item at a time with yield. It is lazy.
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
squares_gen = (x*x for x in range(10000000))
print(next(squares_gen)) # 0
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
for num in fibonacci(20):
print(num, end=" ")
Note: (x*x for x in ...) is a generator expression. [x*x for x in ...] is a list comprehension.
5. Decorators
A decorator takes a function and returns a new, enhanced function. @timer is shorthand for func = timer(func).
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_work():
time.sleep(1)
return "Done"
print(slow_work())
6. Namespaces and Scope
Python follows LEGB: Local → Enclosing → Global → Built-in.
x = 100 # Global
def outer():
x = 50 # Enclosing
def inner():
x = 10 # Local
print(x) # 10
inner()
print(x) # 50
outer()
print(x) # 100
count = 0
def increment():
global count
count += 1
def counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
c = counter()
print(c()) # 1
print(c()) # 2
7. Handle Errors with try and except
try:
num = int(input("Enter a number: "))
result = 100 / num
print("Result:", result)
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("No error occurred.")
finally:
print("This always runs, for cleanup.")
Catch specific exceptions, not bare except:. A bare except hides bugs.
8. User Exceptions
Define your own by inheriting from Exception when your domain has a specific error.
class InvalidMarksError(Exception):
"""Raised when marks are outside 0 to 100."""
pass
def set_marks(marks):
if not 0 <= marks <= 100:
raise InvalidMarksError(f"Marks {marks} are invalid. Must be 0 to 100.")
return f"Marks accepted: {marks}"
try:
print(set_marks(120))
except InvalidMarksError as e:
print("Error:", e)
class InsufficientBalanceError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Need {amount}, but balance is only {balance}")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError(balance, amount)
return balance - amount
9. Putting It All Together
class InvalidAgeError(Exception):
pass
def get_eligible_students(students):
def check_age(student):
name, age = student
if age < 0:
raise InvalidAgeError(f"Age cannot be negative for {name}")
return age >= 18
for student in students:
try:
if check_age(student):
yield student[0]
except InvalidAgeError as e:
print("Skipping:", e)
students = [("Anitha", 20), ("Kumar", 17), ("Priya", -5), ("Ravi", 19)]
print(list(get_eligible_students(students)))
Assignment for Next Class
Write a decorator @validate_marks that checks if a function's argument is between 0 and 100, and raises InvalidMarksError if not.
@validate_marks
def record_score(name, mark):
return f"{name}: {mark}"
print(record_score("Anitha", 92)) # Anitha: 92
# record_score("Kumar", 140) # should raise InvalidMarksError