Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 10 / Stage 2

Pythonic and functional Python

Goal: Write short, clear Python with comprehensions, decorators, generators and context managers, like experienced Python developers do. Time: ~1 hour

What you will learn

  • What "Pythonic" means, and the Zen of Python (import this)
  • Advanced comprehensions: nested, if/else, dict and set, and when to avoid them
  • Handy built-ins: enumerate, zip, any, all, sorted/min/max with key=, * and ** unpacking
  • Functional tools: map, filter, functools.reduce, lambda
  • Closures and nonlocal
  • Decorators: @ syntax, functools.wraps, decorators with arguments, lru_cache
  • Iterators: iter(), next(), StopIteration, __iter__ / __next__
  • Generators: yield, generator expressions, yield from, pipelines
  • itertools: count, islice, chain, groupby, batched, accumulate
  • Context managers: with, __enter__ / __exit__, @contextmanager

Topics in this part

Practice

Python workbench — write and run code here

Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.

Write each answer in its own file with a main() function and the if __name__ == "__main__": guard.


Exercise 1: Order summary with comprehensions

Scenario: An online shop wants quick facts about today's orders. What to do: Using only comprehensions (no for loop that appends):

  1. Build a dict totals of name -> amount and print it.
  2. Build a set of cities and print it sorted.
  3. Build a list of labels "<name>: free delivery" when the amount is ₹1,000 or more, else "<name>: ₹40 delivery". Print one label per line.
  4. Build a list of names in UPPER case, only for orders of ₹1,000 or more. Print it.

Starting data:

ORDERS = [
    ("Asha", "Pune", 1760),
    ("Ravi", "Delhi", 540),
    ("Meera", "Pune", 2999),
    ("Kiran", "Chennai", 820),
]

Sample output:

{'Asha': 1760, 'Ravi': 540, 'Meera': 2999, 'Kiran': 820}
['Chennai', 'Delhi', 'Pune']
Asha: free delivery
Ravi: ₹40 delivery
Meera: free delivery
Kiran: ₹40 delivery
['ASHA', 'MEERA']

💡 Hint: Unpack in the for part: for name, _, amount in ORDERS. The if/else goes at the front, the filter if at the end.


Show the solution to Exercise 1
"""Exercise 1: Order summary with comprehensions.

Shows: dict, set and list comprehensions, with an if/else expression.

Run:   python ex01.py   (macOS/Linux: python3 ex01.py)
"""

ORDERS = [
    ("Asha", "Pune", 1760),
    ("Ravi", "Delhi", 540),
    ("Meera", "Pune", 2999),
    ("Kiran", "Chennai", 820),
]


def main() -> None:
    totals = {name: amount for name, _, amount in ORDERS}
    cities = {city for _, city, _ in ORDERS}
    labels = [
        f"{name}: {'free delivery' if amount >= 1000 else '₹40 delivery'}"
        for name, _, amount in ORDERS
    ]
    big_names = [name.upper() for name, _, amount in ORDERS if amount >= 1000]

    print(totals)
    print(sorted(cities))
    for label in labels:
        print(label)
    print(big_names)


if __name__ == "__main__":
    main()

Exercise 2: Results board

Scenario: A coaching centre prints a ranked results board. What to do:

  1. zip the names and marks, sort by mark (highest first) and print each with its rank using enumerate(..., start=1). Format: f"{rank}. {name:<6} {mark}".
  2. Use any and all to print whether anyone failed and whether everyone passed (pass mark is 35).
  3. Use min(..., key=) to print the student who needs help.
  4. Unpack the sorted names with topper, *others = ... and print both.

Starting data:

NAMES = ["Asha", "Ravi", "Meera", "Kiran"]
MARKS = [91, 34, 85, 78]
PASS_MARK = 35

Sample output:

1. Asha   91
2. Meera  85
3. Kiran  78
4. Ravi   34
Anyone failed? True
Everyone passed? False
Needs help: Ravi 34
Topper: Asha | others: ['Meera', 'Kiran', 'Ravi']

💡 Hint: sorted(zip(NAMES, MARKS), key=lambda pair: pair[1], reverse=True). In the loop, write for rank, (name, mark) in enumerate(...).


Show the solution to Exercise 2
"""Exercise 2: Results board with enumerate, zip, any, all and key=.

Run:   python ex02.py   (macOS/Linux: python3 ex02.py)
"""

NAMES = ["Asha", "Ravi", "Meera", "Kiran"]
MARKS = [91, 34, 85, 78]
PASS_MARK = 35


def main() -> None:
    results = sorted(zip(NAMES, MARKS), key=lambda pair: pair[1], reverse=True)
    for rank, (name, mark) in enumerate(results, start=1):
        print(f"{rank}. {name:<6} {mark}")

    print("Anyone failed?", any(mark < PASS_MARK for mark in MARKS))
    print("Everyone passed?", all(mark >= PASS_MARK for mark in MARKS))
    lowest_name, lowest_mark = min(zip(NAMES, MARKS), key=lambda pair: pair[1])
    print("Needs help:", lowest_name, lowest_mark)

    topper, *others = [name for name, _ in results]
    print("Topper:", topper, "| others:", others)


if __name__ == "__main__":
    main()

Exercise 3: Cart total with map, filter and reduce

Scenario: A grocery app shows the cart with 18% GST. What to do:

  1. Use map to make a list of the item names in UPPER case.
  2. Use filter to keep the items costing ₹100 or more.
  3. Use map to make a list of prices with GST, rounded to whole rupees with round().
  4. Use functools.reduce to add up the GST prices and print Total with GST: ₹2,354 style.
  5. Write the GST list again as a comprehension and print whether it equals the map version.

Starting data:

CART = [("Rice 5kg", 425), ("Pen", 10), ("Headphones", 1499), ("Notebook", 60)]
GST = 0.18

Sample output:

['RICE 5KG', 'PEN', 'HEADPHONES', 'NOTEBOOK']
[('Rice 5kg', 425), ('Headphones', 1499)]
[502, 12, 1769, 71]
Total with GST: ₹2,354
Comprehension gives the same: True

💡 Hint: Each item is a tuple, so the lambda uses item[0] for the name and item[1] for the price. Give reduce a start value of 0.


Show the solution to Exercise 3
"""Exercise 3: Cart total with map, filter and reduce.

Run:   python ex03.py   (macOS/Linux: python3 ex03.py)
"""

from functools import reduce

CART = [("Rice 5kg", 425), ("Pen", 10), ("Headphones", 1499), ("Notebook", 60)]
GST = 0.18


def main() -> None:
    names = list(map(lambda item: item[0].upper(), CART))
    costly = list(filter(lambda item: item[1] >= 100, CART))
    with_gst = list(map(lambda item: round(item[1] * (1 + GST)), CART))
    total = reduce(lambda running, price: running + price, with_gst, 0)

    print(names)
    print(costly)
    print(with_gst)
    print(f"Total with GST: ₹{total:,}")
    same = [round(price * (1 + GST)) for _, price in CART]
    print("Comprehension gives the same:", same == with_gst)


if __name__ == "__main__":
    main()

Exercise 4: Token machines and a budget (closures)

Scenario: A hospital gives tokens per department, and a family app blocks spending over a monthly limit. What to do:

  1. Write make_token_machine(prefix) that returns a function. Each call returns the next token: "OPD-001", "OPD-002", … Each machine counts on its own. Make an "OPD" and a "LAB" machine and print opd(), opd(), lab(), opd() on one line.
  2. Write make_budget(limit) that returns spend(amount). If the amount fits, add it and return "Spent ₹X, left ₹Y"; otherwise do not add it and return "Blocked ₹X (only ₹Y left)". Make a ₹2,000 budget and spend 500, 1200, 400, 300.

Sample output:

OPD-001 OPD-002 LAB-001 OPD-003
Spent ₹500, left ₹1,500
Spent ₹1,200, left ₹300
Blocked ₹400 (only ₹300 left)
Spent ₹300, left ₹0

💡 Hint: Use nonlocal number and nonlocal spent in the inner functions. f"{number:03d}" pads with zeros to 3 digits.


Show the solution to Exercise 4
"""Exercise 4: Token machines and a spending tracker (closures).

Run:   python ex04.py   (macOS/Linux: python3 ex04.py)
"""


def make_token_machine(prefix: str):
    number = 0

    def next_token() -> str:
        nonlocal number
        number += 1
        return f"{prefix}-{number:03d}"

    return next_token


def make_budget(limit: int):
    spent = 0

    def spend(amount: int) -> str:
        nonlocal spent
        if spent + amount > limit:
            return f"Blocked ₹{amount:,} (only ₹{limit - spent:,} left)"
        spent += amount
        return f"Spent ₹{amount:,}, left ₹{limit - spent:,}"

    return spend


def main() -> None:
    opd = make_token_machine("OPD")
    lab = make_token_machine("LAB")
    print(opd(), opd(), lab(), opd())

    spend = make_budget(2000)
    for amount in [500, 1200, 400, 300]:
        print(spend(amount))


if __name__ == "__main__":
    main()

Exercise 5: Logging and retry decorators

Scenario: A payments team wants every call logged, and flaky bank calls retried. What to do:

  1. Write a decorator log_call (with @wraps) that prints -> name(args) before the call and <- name = result after it. Use it on shipping_fee(weight_kg, express=False), which returns 40 + 15 * weight_kg, doubled when express is true. Call shipping_fee(2) and shipping_fee(3, True), then print the function's __name__ and __doc__.
  2. Write a decorator factory retry(times). On ConnectionError it prints attempt N/times failed: <error> and tries again. After times failures it returns "FAILED". Use @retry(times=3) on pay(method) below and print pay("UPI") and pay("CARD").

Starting data:

failures = {"UPI": 2, "CARD": 5}       # how many times each method fails first

def pay(method: str) -> str:
    if failures[method] > 0:
        failures[method] -= 1
        raise ConnectionError("bank timeout")
    return f"paid by {method}"

Give shipping_fee the docstring """Return the shipping fee in rupees.""".

Sample output:

-> shipping_fee(2,)
<- shipping_fee = 70
-> shipping_fee(3, True)
<- shipping_fee = 170
shipping_fee - Return the shipping fee in rupees.
   attempt 1/3 failed: bank timeout
   attempt 2/3 failed: bank timeout
paid by UPI
   attempt 1/3 failed: bank timeout
   attempt 2/3 failed: bank timeout
   attempt 3/3 failed: bank timeout
FAILED

💡 Hint: print(f"-> {func.__name__}{args}") prints the args tuple straight after the name. retry has three layers: retry(times) → decorator(func) → wrapper(*args, **kwargs).


Show the solution to Exercise 5
"""Exercise 5: Logging and retry decorators.

Run:   python ex05.py   (macOS/Linux: python3 ex05.py)
"""

from functools import wraps


def log_call(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"-> {func.__name__}{args}")
        result = func(*args, **kwargs)
        print(f"<- {func.__name__} = {result}")
        return result
    return wrapper


def retry(times: int):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except ConnectionError as error:
                    print(f"   attempt {attempt}/{times} failed: {error}")
            return "FAILED"
        return wrapper
    return decorator


@log_call
def shipping_fee(weight_kg: int, express: bool = False) -> int:
    """Return the shipping fee in rupees."""
    fee = 40 + 15 * weight_kg
    return fee * 2 if express else fee


failures = {"UPI": 2, "CARD": 5}       # how many times each method fails first


@retry(times=3)
def pay(method: str) -> str:
    if failures[method] > 0:
        failures[method] -= 1
        raise ConnectionError("bank timeout")
    return f"paid by {method}"


def main() -> None:
    shipping_fee(2)
    shipping_fee(3, True)
    print(shipping_fee.__name__, "-", shipping_fee.__doc__)
    print(pay("UPI"))
    print(pay("CARD"))


if __name__ == "__main__":
    main()

Exercise 6: Pages and chunks (iterator + generator)

Scenario: A shop's product list is shown a few items per page. What to do:

  1. Write a class Pages(items, per_page) with __iter__ and __next__ that gives the page numbers 1, 2, … (7 items, 3 per page → 3 pages). Print list(Pages(PRODUCTS, 3)).
  2. Write a generator chunks(items, size) that yields lists of at most size items.
  3. Loop over zip(Pages(PRODUCTS, 3), chunks(PRODUCTS, 3)) and print each page.
  4. Make chunks(PRODUCTS, 5), call next() on it twice and print each result, then a third time inside try/except StopIteration and print No more pages.

Starting data:

PRODUCTS = ["Pen", "Pencil", "Eraser", "Ruler", "Stapler", "Glue", "Tape"]

Sample output:

Pages: [1, 2, 3]
Page 1: Pen, Pencil, Eraser
Page 2: Ruler, Stapler, Glue
Page 3: Tape
['Pen', 'Pencil', 'Eraser', 'Ruler', 'Stapler']
['Glue', 'Tape']
No more pages

💡 Hint: Number of pages = (len(items) + per_page - 1) // per_page (division that rounds up). In chunks, use range(0, len(items), size) and slicing.


Show the solution to Exercise 6
"""Exercise 6: Page iterator and a chunking generator.

Run:   python ex06.py   (macOS/Linux: python3 ex06.py)
"""

PRODUCTS = ["Pen", "Pencil", "Eraser", "Ruler", "Stapler", "Glue", "Tape"]


class Pages:
    """Iterator that gives page numbers 1..total_pages for a list."""

    def __init__(self, items: list, per_page: int):
        self.total_pages = (len(items) + per_page - 1) // per_page
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self) -> int:
        if self.current >= self.total_pages:
            raise StopIteration
        self.current += 1
        return self.current


def chunks(items: list, size: int):
    """Yield lists of at most `size` items."""
    for start in range(0, len(items), size):
        yield items[start:start + size]


def main() -> None:
    print("Pages:", list(Pages(PRODUCTS, 3)))
    for page, chunk in zip(Pages(PRODUCTS, 3), chunks(PRODUCTS, 3)):
        print(f"Page {page}: {', '.join(chunk)}")

    gen = chunks(PRODUCTS, 5)
    print(next(gen))
    print(next(gen))
    try:
        next(gen)
    except StopIteration:
        print("No more pages")


if __name__ == "__main__":
    main()

Exercise 7: Sales report with a generator pipeline and itertools

Scenario: A shop exports messy sales lines: comments, blank lines and broken rows mixed in. What to do:

  1. Write a generator clean(lines) that skips blank lines, lines starting with # and lines that do not have exactly two commas.
  2. Write a generator parse(lines) that yields dicts with day, city and amount (as int).
  3. Build sales = list(parse(clean(RAW_LINES))) and print how many rows are valid.
  4. Use groupby (sort first!) to print the total per city.
  5. The data is already in day order: use groupby on day to get each day's total, then accumulate for the running total. Print both.

Starting data:

RAW_LINES = [
    "# date,city,amount",
    "2026-03-01,Pune,1200",
    "2026-03-01,Delhi,800",
    "",
    "2026-03-02,Pune,450",
    "2026-03-02,Chennai,990",
    "bad line",
    "2026-03-03,Delhi,300",
    "2026-03-03,Pune,150",
]

Sample output:

Valid rows: 6
By city:
  Chennai  ₹990
  Delhi    ₹1,100
  Pune     ₹1,800
Running total by day:
  2026-03-01  ₹2,000  (so far ₹2,000)
  2026-03-02  ₹1,440  (so far ₹3,440)
  2026-03-03  ₹450  (so far ₹3,890)

💡 Hint: City line: f" {city:<8} ₹{total:,}". Day line: f" {day} ₹{total:,} (so far ₹{so_far:,})". zip the day totals with the accumulate result to print them side by side.


Show the solution to Exercise 7
"""Exercise 7: Sales report with a generator pipeline and itertools.

Run:   python ex07.py   (macOS/Linux: python3 ex07.py)
"""

from itertools import accumulate, groupby

RAW_LINES = [
    "# date,city,amount",
    "2026-03-01,Pune,1200",
    "2026-03-01,Delhi,800",
    "",
    "2026-03-02,Pune,450",
    "2026-03-02,Chennai,990",
    "bad line",
    "2026-03-03,Delhi,300",
    "2026-03-03,Pune,150",
]


def clean(lines):
    for line in lines:
        if line and not line.startswith("#") and line.count(",") == 2:
            yield line


def parse(lines):
    for line in lines:
        day, city, amount = line.split(",")
        yield {"day": day, "city": city, "amount": int(amount)}


def main() -> None:
    sales = list(parse(clean(RAW_LINES)))
    print("Valid rows:", len(sales))

    print("By city:")
    by_city = sorted(sales, key=lambda s: s["city"])
    for city, rows in groupby(by_city, key=lambda s: s["city"]):
        total = sum(row["amount"] for row in rows)
        print(f"  {city:<8} ₹{total:,}")

    print("Running total by day:")
    day_totals = []
    for day, rows in groupby(sales, key=lambda s: s["day"]):   # already in day order
        day_totals.append((day, sum(row["amount"] for row in rows)))
    running = accumulate(total for _, total in day_totals)
    for (day, total), so_far in zip(day_totals, running):
        print(f"  {day}  ₹{total:,}  (so far ₹{so_far:,})")


if __name__ == "__main__":
    main()

Exercise 8: Audit log and a temporary setting (context managers)

Scenario: An accounts app logs every task, and some reports need a different setting just for a moment. What to do:

  1. Write a class AuditLog(task) used with with. On enter it prints [audit] start <task>. On exit it prints [audit] <task> OK, or [audit] <task> FAILED: <error> if the block raised an error. It must not hide the error.
  2. Use it for "monthly invoice" (prints creating invoice inside), then for "refund" where the block raises ValueError("amount is negative"). Catch the error outside and print refund error handled.
  3. Write temporary_setting(key, value) with @contextmanager. It changes SETTINGS[key], yields SETTINGS, and always puts the old value back.
  4. Print SETTINGS before, inside (with gst 5) and after. Then use it to set currency to "USD" with a block that raises RuntimeError("export failed"); catch it and show the currency is back to INR.

Starting data:

SETTINGS = {"gst": 18, "currency": "INR"}

Sample output:

[audit] start monthly invoice
  creating invoice
[audit] monthly invoice OK
[audit] start refund
[audit] refund FAILED: amount is negative
  refund error handled
Before: {'gst': 18, 'currency': 'INR'}
Inside: {'gst': 5, 'currency': 'INR'}
After:  {'gst': 18, 'currency': 'INR'}
Error: export failed | currency is INR

💡 Hint: In __exit__, exc_type is None means no error happened; return False. In the generator, put the restore line in finally.

Show the solution to Exercise 8
"""Exercise 8: Two context managers: a class and @contextmanager.

Run:   python ex08.py   (macOS/Linux: python3 ex08.py)
"""

from contextlib import contextmanager

SETTINGS = {"gst": 18, "currency": "INR"}


class AuditLog:
    """Print when a task starts and how it ended."""

    def __init__(self, task: str):
        self.task = task

    def __enter__(self):
        print(f"[audit] start {self.task}")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is None:
            print(f"[audit] {self.task} OK")
        else:
            print(f"[audit] {self.task} FAILED: {exc_value}")
        return False


@contextmanager
def temporary_setting(key: str, value):
    old = SETTINGS[key]
    SETTINGS[key] = value
    try:
        yield SETTINGS
    finally:
        SETTINGS[key] = old


def main() -> None:
    with AuditLog("monthly invoice"):
        print("  creating invoice")

    try:
        with AuditLog("refund"):
            raise ValueError("amount is negative")
    except ValueError:
        print("  refund error handled")

    print("Before:", SETTINGS)
    with temporary_setting("gst", 5) as settings:
        print("Inside:", settings)
    print("After: ", SETTINGS)

    try:
        with temporary_setting("currency", "USD"):
            raise RuntimeError("export failed")
    except RuntimeError as error:
        print("Error:", error, "| currency is", SETTINGS["currency"])


if __name__ == "__main__":
    main()

Common mistakes

Mistake Why it is wrong Fix
for i in range(len(items)): Noisy and easy to get off by one for i, item in enumerate(items):
[print(x) for x in items] Builds a useless list of None Use a normal for loop
A 3-level comprehension on one line Hard to read and debug Split into a loop or helper function
count += 1 in an inner function, no nonlocal UnboundLocalError Add nonlocal count
Decorator without @wraps(func) Function loses its name and docstring Add @wraps(func) above wrapper
@timer() vs @timer mixed up A decorator with no settings must not be called Use () only for factories like @retry(times=3)
Looping over a generator twice Second loop gets nothing Make a new generator, or list() it once
groupby on unsorted data Same key appears in many groups sorted(..., key=f) first, with the same f
Clean-up after yield without try/finally Skipped if the block raises an error Put clean-up in finally

Quick recap

  • Pythonic = readable code that uses the language's own tools; readability beats cleverness.
  • Comprehensions build lists, dicts and sets; x if c else y goes at the front, filters at the end.
  • enumerate, zip, any, all and key= replace most index loops.
  • map/filter are lazy; comprehensions are usually clearer; reduce folds to one value.
  • A closure remembers outer variables; nonlocal lets it change them.
  • A decorator wraps a function; use @wraps; add a layer for arguments; @cache remembers results.
  • Iterators hand out items with next() until StopIteration; generators (yield) are the easy way to write them.
  • with guarantees clean-up; write managers with __enter__/__exit__ or @contextmanager.

Checklist

  • I can rewrite an index loop with enumerate or zip.
  • I can write dict, set and nested comprehensions, and know when a loop is clearer.
  • I can use map, filter and reduce, and choose between them and a comprehension.
  • I can write a closure that uses nonlocal.
  • I can write a decorator with @wraps, and one that takes arguments.
  • I can write a generator and chain generators into a pipeline.
  • I can use groupby correctly (sorted first) and batched.
  • I can write a context manager with a class and with @contextmanager.

Search the guide