CIPHERCODE.AI · PYTHON INTERMEDIATE

Think in objects

Move from scripts that work to programs that are organised, testable and ready to grow.

  • 9 modules
  • ~9 hours
  • 3 projects

What you will be able to do

  • Design functions with flexible arguments, closures and type hints
  • Write comprehensions and use iteration tools like zip, enumerate and itertools
  • Model real-world ideas with classes, inheritance and dunder methods
  • Handle errors on purpose with custom exceptions and read and write JSON and CSV files
  • Organise code into modules and packages inside an isolated virtual environment
  • Use the standard library (collections, datetime, re, argparse, functools) instead of reinventing it
  • Call web APIs and explore tabular data with requests, NumPy and pandas
  • Debug with tracebacks, logging and pdb, and protect your code with unittest and pytest

Before you start

  • Variables, strings, numbers, booleans and f-strings
  • if/elif/else, for and while loops
  • Lists, tuples, dictionaries and sets
  • Writing simple functions, try/except, and installing packages with pip

You are comfortable with variables, loops, lists, dictionaries and basic functions, and you want to write cleaner, bigger programs.

At the beginner level you learned to make Python do things: store data, make decisions, repeat work and wrap steps in functions. That is enough to write useful scripts. It is not yet enough to write a program that ten other people can read, change and trust.

This level is about structure. You will learn how functions really work, how to write compact loops, how to model real things as classes, how to handle files and failures without crashing, how to split code across modules, how to talk to web APIs and analyse data, and how to prove your code works with tests. Every module ends with a practice task, a short quiz and a prompt you can paste into an AI tutor.

Module 1

Functions in depth

Go beyond def: flexible arguments, functions as values, closures, type hints and the mutable default trap.

About 55 minutes

You already know that a function packages a few lines of code under a name. At this level, functions become the main way you shape a program. You will pass them around like data, build small specialised functions out of general ones, and design their inputs so other people (and future you) cannot misuse them by accident.

The mental model for this whole module: a function is an object. def creates a function object and attaches a name to it, exactly like x = 5 attaches the name x to a number. Once you really believe that, everything below stops feeling like special syntax.

1. Parameters: positional, keyword and default

A parameter is the name in the function definition. An argument is the value you pass in the call. Python lets you pass arguments by position (make_order("latte", 2)) or by name (make_order(item="latte", quantity=2)). A parameter with a default value (quantity=1) becomes optional.

orders.py
def make_order(item, quantity=1, size="medium"):
    # item is required; quantity and size have defaults
    return f"{quantity} x {size} {item}"

print(make_order("latte"))                      # only the required one
print(make_order("latte", 2))                   # quantity by position
print(make_order("latte", size="large"))        # skip quantity, set size by name
print(make_order(size="small", item="mocha", quantity=3))  # all by name, any order
Notice the last call: when you use names, the order no longer matters. That is why keyword arguments make calls easier to read.

Rules to remember: required parameters must come before parameters with defaults, and once you start using names in a call, every argument after that must also use a name. Python checks this when it reads your code, before anything runs.

2. *args and **kwargs: accepting any number of arguments

Sometimes you cannot know how many values will arrive. A café bill might have two items or twenty. Putting * in front of a parameter name tells Python: collect all extra positional arguments into a tuple. Putting ** in front means: collect all extra keyword arguments into a dictionary. The names args and kwargs are only conventions; the stars do the work.

bill.py
def total_bill(*prices, tax_rate=0.05, **extras):
    # prices  -> tuple of every positional argument
    # extras  -> dict of every unknown keyword argument (tip=20 becomes {"tip": 20})
    subtotal = sum(prices)
    extra_cost = sum(extras.values())
    total = (subtotal + extra_cost) * (1 + tax_rate)
    print("prices:", prices)
    print("extras:", extras)
    return round(total, 2)

print(total_bill(120, 80, 45))
print(total_bill(120, 80, tax_rate=0.18, tip=20, parcel=10))
Line-by-line: *prices swallows 120, 80, 45 into (120, 80, 45). tax_rate sits after the star, so it can only be given by name. In the second call, tip and parcel match no named parameter, so they land in extras.

The stars also work in the opposite direction, at the call site. f(*my_list) unpacks a list into separate positional arguments and f(**my_dict) unpacks a dictionary into keyword arguments.

unpacking_calls.py
def total_bill(*prices, tax_rate=0.05, **extras):
    return round((sum(prices) + sum(extras.values())) * (1 + tax_rate), 2)

items = [150, 90, 60]
fees = {"parcel": 10, "tip": 15}

# Same as total_bill(150, 90, 60, parcel=10, tip=15)
print(total_bill(*items, **fees))
Syntax in defWhat it collectsType you receive
def f(a, b)exactly the arguments namednormal variables
def f(*args)extra positional argumentstuple
def f(**kwargs)extra keyword argumentsdict
def f(a, /, b, *, c)a: position only, b: either, c: name onlynormal variables

3. Positional-only and keyword-only parameters

A bare * in the parameter list means everything after me must be passed by name. A / means everything before me must be passed by position. These are design tools. Use keyword-only for options that would be confusing as bare values (book_seat("Asha", 3, True) — true what?). Use positional-only when the parameter name is not meaningful to callers.

seats.py
def book_seat(name, /, row, *, vegetarian=False):
    meal = "veg" if vegetarian else "regular"
    return f"{name}: row {row}, {meal} meal"

print(book_seat("Asha", 3))
print(book_seat("Ravi", row=7, vegetarian=True))

# Each of these breaks one rule on purpose; we catch the error to read it
try:
    book_seat(name="Asha", row=3)          # name is positional-only
except TypeError as e:
    print("TypeError:", e)

try:
    book_seat("Asha", 3, True)             # vegetarian must be named
except TypeError as e:
    print("TypeError:", e)
trap.py
def add_item_bad(item, cart=[]):      # the [] is created ONE time
    cart.append(item)
    return cart

print(add_item_bad("tea"))
print(add_item_bad("coffee"))         # tea is still there!
print(add_item_bad.__defaults__)      # the shared list lives on the function

def add_item(item, cart=None):        # safe pattern: None means "make a new one"
    if cart is None:
        cart = []
    cart.append(item)
    return cart

print(add_item("tea"))
print(add_item("coffee"))             # independent carts
The fix is always the same: default to None and create the list inside the function body. Use this for lists, dicts and sets.

4. Functions are values

Because a function is an object, you can store it in a variable, put it in a list or dictionary, pass it into another function and return it from one. Functions that take or return other functions are called higher-order functions. You have already used some: sorted(..., key=...) takes a function.

lambda is a shortcut for writing a tiny, nameless function that is a single expression: lambda p: p * 0.9 means take p, give back p times 0.9. If you need more than one line or want to reuse it with a clear name, use def.

strategies.py
# A dictionary of strategies: each value is a function
discounts = {
    "none":     lambda price: price,
    "student":  lambda price: price * 0.90,
    "festival": lambda price: price - 50 if price > 200 else price,
}

def final_price(price, plan="none"):
    apply = discounts[plan]       # look up the function...
    return apply(price)           # ...and call it

print(final_price(500, "student"))
print(final_price(500, "festival"))
print(final_price(150, "festival"))

# sorted() takes a function as its key argument
marks = [("Asha", 82), ("Ravi", 91), ("Meena", 78)]
print(sorted(marks, key=lambda row: row[1], reverse=True))
This 'dictionary of functions' pattern replaces long if/elif chains. Adding a new discount means adding one line to the dictionary, not editing the logic.

5. Closures: functions that remember

When you define a function inside another function, the inner one can use the outer one's variables, even after the outer function has finished. The inner function carries those variables with it. That bundle is called a closure. Picture a coffee token machine: make_counter() builds a machine, and each machine remembers its own count privately.

closures.py
def make_counter(start=0):
    count = start                  # lives in the enclosing function

    def step():
        nonlocal count             # we want to rebind it, not create a new local
        count += 1
        return count

    return step                    # return the inner function itself

orders_today = make_counter()
tokens = make_counter(100)

print(orders_today(), orders_today(), orders_today())
print(tokens(), tokens())          # separate machine, separate memory

def make_multiplier(factor):
    return lambda x: x * factor

double = make_multiplier(2)
tax = make_multiplier(1.18)
print(double(21), tax(100))
nonlocal is needed only when you assign to the outer variable. Reading it needs no keyword. Without nonlocal, count += 1 raises UnboundLocalError.

6. Type hints and docstrings

A type hint says what kind of value a parameter or return should be: def average(marks: list[float]) -> float. Python does not enforce hints when running. They are documentation that editors and tools like mypy can check, and they make your intent obvious. A docstring is a string literal placed first inside the function. It is stored on the function as __doc__ and shown by help().

hints.py
def average(marks: list[float], drop_lowest: bool = False) -> float:
    """Return the mean of marks.

    If drop_lowest is True, the smallest mark is ignored first.
    Raises ValueError when there are no marks to average.
    """
    if not marks:
        raise ValueError("marks must not be empty")
    values = sorted(marks)[1:] if drop_lowest and len(marks) > 1 else marks
    return sum(values) / len(values)

print(average([70, 80, 90]))
print(average([40, 80, 90], drop_lowest=True))
print(average.__doc__.splitlines()[0])
print(average.__annotations__)

# Hints are NOT enforced at runtime:
print(average((60, 70)))       # a tuple works fine even though we said list

7. Reading the errors you will meet

Most function mistakes produce a TypeError whose message tells you exactly what is wrong. Learn to read them like a checklist.

errors.py
def make_order(item, quantity=1, size="medium"):
    return f"{quantity} x {size} {item}"

def attempt(label, call):
    try:
        call()
    except Exception as e:
        print(f"{label}: {type(e).__name__}: {e}")

attempt("missing argument", lambda: make_order())
attempt("too many args   ", lambda: make_order("tea", 1, "small", "extra"))
attempt("unknown keyword ", lambda: make_order("tea", flavour="mint"))
attempt("given twice     ", lambda: make_order("tea", item="coffee"))
Each message names the function and the exact problem. Fix by supplying the missing value, removing the extra one, correcting the keyword spelling, or passing the value only once.

Remember this

  • A function is an object: store it, pass it and return it.
  • *args collects extra positional arguments into a tuple; **kwargs collects keyword arguments into a dict.
  • Use * to force keyword-only and / to force positional-only parameters.
  • Never use a list or dict as a default value; use None and create it inside.
  • A closure remembers variables from the function that created it; nonlocal lets it change them.
  • Type hints and docstrings document intent but are not enforced at runtime.

Your turn

Write describe_scores(*marks, pass_mark=40) that returns a dictionary with the keys highest, lowest, average (rounded to 1 decimal) and passed (how many marks are at least pass_mark). Add type hints and a docstring. Then call it with * unpacking on the list [35, 72, 90, 41].

Use max(), min(), sum() and len(). A generator or list comprehension can count passes. Remember pass_mark must be given by name because it comes after *marks.

solution.py
def describe_scores(*marks: float, pass_mark: float = 40) -> dict:
    """Summarise any number of marks."""
    return {
        "highest": max(marks),
        "lowest": min(marks),
        "average": round(sum(marks) / len(marks), 1),
        "passed": sum(1 for m in marks if m >= pass_mark),
    }

scores = [35, 72, 90, 41]
print(describe_scores(*scores))
print(describe_scores(*scores, pass_mark=60))

Check yourself

What does <code>def f(*args)</code> give you inside the function?

Why is <code>def add(item, cart=[])</code> dangerous?

In a closure, when do you need the <code>nonlocal</code> keyword?

Ask the CipherCode AI tutor

Act as my Python tutor. Give me 5 small exercises on *args, **kwargs, keyword-only parameters and closures, one at a time, starting easy. Wait for my answer before showing the next, and explain any mistake using the exact error message Python would show.

Next module

Module 2

Comprehensions and iteration

Write compact loops with comprehensions, and walk data cleanly with enumerate, zip, sorted, any/all and itertools.

About 55 minutes

Most programs spend their time looping over data: filtering rows, transforming values, pairing lists, ranking results. Python gives you a toolbox for doing this clearly and in very few lines. Learning it is what makes intermediate code look "Pythonic" instead of like translated C.

The central idea is iteration. Anything you can put after for ... in is an iterable: lists, strings, dictionaries, files, ranges and more. The tools in this module all accept iterables, so once you learn them they work everywhere.

1. List comprehensions

A list comprehension builds a new list in one expression. Read it almost like English: [expression for item in iterable if condition] means give me expression, for each item, but only if condition is true. Compare the long way and the short way for an expense tracker.

expenses.py
expenses = [250, 40, 1200, 90, 15, 640]

# The loop version
big_loop = []
for amount in expenses:
    if amount >= 100:
        big_loop.append(amount)

# The comprehension version: same result
big = [amount for amount in expenses if amount >= 100]

print(big_loop == big, big)

# Transform every item (no filter)
with_gst = [round(a * 1.18, 2) for a in expenses]
print(with_gst)

# Transform AND filter
small_labels = [f"Rs {a}" for a in expenses if a < 100]
print(small_labels)
Line-by-line: the part before for is what goes into the new list, for amount in expenses is the loop, and the optional if at the end decides which items are kept.

If you want a different value rather than dropping items, use a conditional expression before the for: [x if test else y for x in data]. The position matters. An if at the end filters; an if ... else at the front chooses a value.

grading.py
marks = [35, 72, 90, 41, 28]

grades = ["pass" if m >= 40 else "fail" for m in marks]   # value choice, keeps all 5
passed_only = [m for m in marks if m >= 40]               # filter, keeps 3

print(grades)
print(passed_only)

# Nested loops: the order reads the same as nested for-statements
pairs = [(row, seat) for row in "AB" for seat in (1, 2, 3)]
print(pairs)

2. Dictionary and set comprehensions

The same idea works with curly braces. {key: value for ...} builds a dictionary and {value for ...} builds a set (which keeps only unique values).

dict_set_comp.py
students = ["Asha", "Ravi", "Meena", "Kabir"]
scores = [82, 91, 78, 91]

# dict comprehension: name -> score
report = {name: score for name, score in zip(students, scores)}
print(report)

# invert a dictionary (swap keys and values) - values must be unique to keep everything
lengths = {name: len(name) for name in students}
print(lengths)

# set comprehension: unique scores only
unique_scores = {s for s in scores}
print(sorted(unique_scores))

# filter inside a dict comprehension
toppers = {n: s for n, s in report.items() if s > 80}
print(toppers)

3. Generator expressions: lazy comprehensions

Swap the square brackets for round ones and you get a generator expression. It does not build the whole list in memory. It produces one value at a time, only when asked. That is perfect when you only need to feed the values into something like sum(), max() or any().

generators.py
expenses = [250, 40, 1200, 90, 15, 640]

total_big = sum(a for a in expenses if a >= 100)   # no brackets needed inside a call
print(total_big)

gen = (a * 2 for a in expenses)
print(next(gen), next(gen))      # values are made on demand
print(list(gen))                 # the remaining four
print(list(gen))                 # exhausted: nothing left
A generator can be used only once. The second list(gen) is empty because the first one already consumed everything. If you need to loop twice, use a list.

4. enumerate and zip

Beginners often write for i in range(len(items)) to get an index. enumerate does this directly and gives you the index and the item together. zip walks two or more iterables side by side, like the teeth of a zipper, and stops when the shortest one ends.

enumerate_zip.py
menu = ["latte", "mocha", "espresso"]
prices = [180, 210, 120]

for number, item in enumerate(menu, start=1):    # start=1 for human-friendly numbering
    print(number, item)

for item, price in zip(menu, prices):
    print(f"{item:<10} Rs {price}")

# zip stops at the shortest input - extra items are silently ignored
print(list(zip([1, 2, 3], ["a", "b"])))

# Python 3.10+: ask zip to complain instead
try:
    list(zip([1, 2, 3], ["a", "b"], strict=True))
except ValueError as e:
    print("ValueError:", e)

5. Sorting with key

sorted() returns a new sorted list and leaves the original alone; list.sort() sorts in place and returns None (a classic bug is writing x = x.sort()). The key argument takes a function that turns each item into the value to compare by. reverse=True flips the order.

sorting.py
batters = [("Kohli", 82.5), ("Rohit", 48.0), ("Gill", 66.3), ("Rahul", 48.0)]

by_average = sorted(batters, key=lambda b: b[1], reverse=True)
print(by_average)

# Sort by two things: average descending, then name ascending for ties
ranked = sorted(batters, key=lambda b: (-b[1], b[0]))
print(ranked)

words = ["banana", "Apple", "cherry"]
print(sorted(words))                        # uppercase letters sort before lowercase
print(sorted(words, key=str.lower))         # fix: compare in lowercase
print(sorted(words, key=len))               # by length, ties keep original order
sorted is stable: items that compare equal keep their original relative order. The tuple trick (-b[1], b[0]) sorts by several fields at once.

6. any, all and unpacking

any(iterable) is true if at least one item is truthy; all(iterable) is true if every item is. With a generator expression they answer yes/no questions about data in one line, and they stop early as soon as the answer is known. Unpacking assigns the parts of a sequence to several names at once, and the starred name *rest soaks up whatever is left over.

any_all_unpack.py
marks = [35, 72, 90, 41]

print(any(m < 40 for m in marks))     # is somebody failing?
print(all(m >= 30 for m in marks))    # is everybody above 30?
print(all([]), any([]))               # empty: all is True, any is False

first, second, *others = marks
print(first, second, others)

*start, last = marks
print(start, last)

name, (maths, science) = "Asha", (88, 92)    # nested unpacking
print(name, maths, science)

a, b = 1, 2
a, b = b, a                                  # the swap idiom - no temporary variable
print(a, b)

try:
    x, y = [1, 2, 3]
except ValueError as e:
    print("ValueError:", e)

7. itertools: ready-made iteration tools

The itertools module is a standard-library collection of building blocks. You do not need to memorise it; knowing the five below covers most needs.

itertools_tour.py
from itertools import chain, islice, groupby, product, combinations

morning = ["tea", "coffee"]
evening = ["mocha", "latte"]
print(list(chain(morning, evening)))                  # one long iterable

print(list(islice(range(100), 5)))                    # first 5 only - no slicing needed

sizes = ["S", "M"]
milks = ["oat", "dairy"]
print(list(product(sizes, milks)))                    # every combination of choices

print(list(combinations(["A", "B", "C"], 2)))         # unique pairs, order ignored

# groupby groups CONSECUTIVE items, so sort first
orders = [("tea", 1), ("latte", 2), ("tea", 3), ("latte", 4)]
orders.sort(key=lambda o: o[0])
for drink, group in groupby(orders, key=lambda o: o[0]):
    print(drink, [qty for _, qty in group])
The most common groupby mistake is forgetting to sort first. It only groups items that sit next to each other.

8. The walrus operator, briefly

The walrus operator := assigns a value and lets you use it in the same expression. It is handy when you would otherwise compute something twice.

walrus.py
expenses = [250, 40, 1200, 90]

# Without walrus we compute round(...) twice; with it, once
taxed = [t for a in expenses if (t := round(a * 1.18)) > 100]
print(taxed)

if (n := len(expenses)) > 3:
    print(f"Many expenses: {n}")

Remember this

  • [expr for x in data if cond] builds a list; use if-else before the for to choose values.
  • Dict and set comprehensions use curly braces; generator expressions use parentheses and are lazy and single-use.
  • enumerate gives index and item; zip pairs iterables and stops at the shortest (strict=True raises instead).
  • sorted returns a new list; list.sort() returns None. Use key= and tuples to sort by several fields.
  • any and all answer yes/no questions in one line; *rest in unpacking collects the leftovers.
  • Sort before groupby, because it only groups neighbouring items.

Your turn

Given orders = [('tea', 30), ('latte', 180), ('tea', 30), ('mocha', 210), ('latte', 180)], use comprehensions and one itertools or built-in tool to print: (1) a dictionary of total revenue per drink, (2) a sorted list of unique drink names, and (3) whether any single order is above Rs 200.

Start with a set comprehension for unique drink names. Then build the dictionary with a dict comprehension that sums the prices of matching orders. Use any() for part 3.

solution.py
orders = [("tea", 30), ("latte", 180), ("tea", 30), ("mocha", 210), ("latte", 180)]

drinks = sorted({name for name, _ in orders})
revenue = {d: sum(price for name, price in orders if name == d) for d in drinks}

print(revenue)
print(drinks)
print(any(price > 200 for _, price in orders))

Check yourself

What is the difference between <code>[x for x in data if x > 0]</code> and <code>[x if x > 0 else 0 for x in data]</code>?

What does <code>list(zip([1, 2, 3], ['a', 'b']))</code> return?

Why does <code>itertools.groupby</code> usually need sorted input?

Ask the CipherCode AI tutor

I am learning Python comprehensions, zip, enumerate and itertools. Show me 4 loops written the long way with a for statement, and ask me to rewrite each as a comprehension or built-in. Then tell me whether my version is more readable or whether a plain loop would have been better.

Next module

Module 3

OOP: classes and objects

Model real-world things as classes: attributes hold data, methods hold behaviour, and each object keeps its own state.

About 60 minutes

So far you have kept data in dictionaries and behaviour in separate functions. That works until a program has many kinds of things: bank accounts, library books, students, orders. Passing a dictionary into twenty functions makes it hard to know which function is allowed to do what, and easy to break the data by accident.

Object-oriented programming (OOP) solves this by bundling data and the functions that work on it into one unit. A class is the blueprint; an object (or instance) is one thing built from it. Think of a class as the architect's plan for a house and each object as an actual house: same plan, but each has its own owner, colour and furniture.

1. Your first class

book.py
class Book:
    """A book in a small library."""

    def __init__(self, title, author, copies=1):
        self.title = title            # attribute: data stored on THIS object
        self.author = author
        self.copies = copies

    def lend(self):                   # method: behaviour that works on this object
        if self.copies == 0:
            return "No copies left"
        self.copies -= 1
        return f"Lent '{self.title}'. Copies left: {self.copies}"

# Create two separate objects from the same blueprint
b1 = Book("Wings of Fire", "A. P. J. Abdul Kalam", copies=2)
b2 = Book("Malgudi Days", "R. K. Narayan")

print(b1.lend())
print(b1.lend())
print(b1.lend())
print(b2.copies)                      # untouched: objects keep separate state
print(type(b1), isinstance(b1, Book))
Walkthrough: class Book: defines the blueprint. Calling Book(...) creates a new empty object, then automatically runs __init__ to fill it in. self is that new object. b1.lend() is Python shorthand for Book.lend(b1), which is why self is the first parameter.

2. Understanding self and __init__

self is not a keyword. It is simply the conventional name for the first parameter of an instance method, and Python fills it in for you with the object before the dot. Inside a method, self.copies means the copies of this particular book. Without self., you would just create a local variable that disappears when the method ends.

__init__ is the initialiser. It runs once, right after the object is created, and its job is to set the starting attributes. It does not return anything. Programmers often (loosely) call it the constructor.

self_demo.py
class Counter:
    def __init__(self):
        self.value = 0

    def bump_wrong(self):
        value = self.value + 1        # BUG: local variable, self.value never changes

    def bump(self):
        self.value += 1

c = Counter()
c.bump_wrong()
print(c.value)
c.bump()
print(c.value)

# Method call = function call with the object as the first argument
c2 = Counter()
Counter.bump(c2)
print(c2.value)

3. Instance attributes vs class attributes

An instance attribute (set with self.x = ...) belongs to one object. A class attribute (set directly in the class body) is shared by all objects and is good for constants and counters. If you assign to a name through an instance, Python creates a new instance attribute that hides the class one, but it does not change the shared value.

class_attr.py
class Account:
    bank_name = "CipherBank"          # class attribute: shared
    total_accounts = 0                # shared counter

    def __init__(self, owner, balance=0):
        self.owner = owner            # instance attributes: per object
        self.balance = balance
        Account.total_accounts += 1   # change the shared one through the CLASS

a = Account("Asha", 5000)
b = Account("Ravi")

print(a.bank_name, b.bank_name, Account.total_accounts)

a.bank_name = "Private Bank"          # creates an instance attribute on a only
print(a.bank_name, b.bank_name, Account.bank_name)
print(a.__dict__)                     # where instance attributes live
Shadowing is why self.total_accounts += 1 would have been a bug: it would create a new instance attribute instead of updating the shared counter.

4. Making objects printable: __repr__ and __str__

By default, printing an object shows something unhelpful like <__main__.Book object at 0x7f...>. Two special methods fix this. __str__ returns a friendly string for users and is what print() and str() use. __repr__ returns an unambiguous string for developers, ideally one that looks like the code that rebuilds the object; it is what the console and debuggers show, and it is the fallback if __str__ is missing.

repr_demo.py
class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def average(self):
        return sum(self.marks) / len(self.marks)

    def __repr__(self):               # for developers: precise
        return f"Student(name={self.name!r}, marks={self.marks!r})"

    def __str__(self):                # for users: readable
        return f"{self.name} (avg {self.average():.1f})"

s = Student("Meena", [78, 85, 92])
print(s)                              # uses __str__
print(repr(s))                        # uses __repr__
print([s])                            # containers show repr of their items
print(f"{s!r}")
The !r inside an f-string means use repr, so strings show their quotes. If you write only one of the two, write __repr__.

5. Encapsulation: protecting your data

Encapsulation means keeping an object's internals behind a controlled doorway so the rest of the program cannot put it into an invalid state. Python is relaxed about this and relies on naming conventions. A single leading underscore (_balance) says internal, please do not touch. A double leading underscore (__balance) triggers name mangling, which renames it to _ClassName__balance to avoid accidental clashes in subclasses. It is not true security, just a stronger hint.

wallet.py
class Wallet:
    def __init__(self, owner, opening_balance=0):
        self.owner = owner
        self._balance = opening_balance        # internal by convention

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

    def withdraw(self, amount):
        if amount > self._balance:
            raise ValueError("Insufficient funds")
        self._balance -= amount

    def balance(self):
        return self._balance

w = Wallet("Kabir", 500)
w.deposit(250)
print(w.balance())

try:
    w.withdraw(5000)
except ValueError as e:
    print("ValueError:", e)

# The underscore is a request, not a lock:
w._balance = -999
print(w.balance())
The rules of the wallet (never negative, deposits positive) live in one place. Anyone using deposit() gets those rules for free. That is the real benefit of encapsulation.

6. Putting it together: a small design

A good first design question is: what are the nouns in my problem? Those become classes. What facts does each one know? Those become attributes. What can each one do? Those become methods. A library has Books and Members and a Library that holds them.

library.py
class Book:
    def __init__(self, title, copies=1):
        self.title = title
        self.copies = copies

    def __repr__(self):
        return f"Book({self.title!r}, copies={self.copies})"

class Library:
    def __init__(self, name):
        self.name = name
        self.books = {}                      # title -> Book (own dict per library)

    def add(self, title, copies=1):
        if title in self.books:
            self.books[title].copies += copies
        else:
            self.books[title] = Book(title, copies)

    def lend(self, title):
        book = self.books.get(title)
        if book is None:
            return f"'{title}' is not in the catalogue"
        if book.copies == 0:
            return f"'{title}' is out of stock"
        book.copies -= 1
        return f"Enjoy '{title}'"

lib = Library("City Library")
lib.add("Godaan", 1)
lib.add("Godaan", 1)             # adds a copy instead of duplicating
print(lib.lend("Godaan"))
print(lib.lend("Godaan"))
print(lib.lend("Godaan"))
print(lib.lend("Ramayana"))
print(lib.books)

Common errors to recognise

  • TypeError: Book.lend() takes 0 positional arguments but 1 was given — you forgot self in the method definition.
  • AttributeError: 'Book' object has no attribute 'copies' — you never set self.copies in __init__, or misspelled it.
  • TypeError: __init__() missing 1 required positional argument: 'author' — you created the object without every required value.
  • NameError: name 'copies' is not defined inside a method — you wrote copies instead of self.copies.

Remember this

  • A class is a blueprint; each call like Book(...) makes a separate object with its own attributes.
  • self is the object before the dot; set per-object data with self.name = ... in __init__.
  • Class attributes are shared by all objects; instance attributes belong to one object.
  • Define __repr__ for developers (and __str__ for users) so printing objects is useful.
  • A leading underscore marks an attribute as internal; encapsulation keeps rules in one place.
  • Find classes by looking for nouns in the problem, and methods by looking for verbs.

Your turn

Create a class BankAccount with owner and a private-by-convention balance. Add deposit(amount), withdraw(amount) (raise ValueError if the money is not available or the amount is not positive) and a __str__ that shows Asha: Rs 1500. Make an account, deposit 500, withdraw 200, and print it.

Store the balance as self._balance. Validate amount first, then change the balance. Use an f-string in __str__.

solution.py
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Amount must be positive")
        self._balance += amount

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("Amount must be positive")
        if amount > self._balance:
            raise ValueError("Insufficient funds")
        self._balance -= amount

    def __str__(self):
        return f"{self.owner}: Rs {self._balance}"

acct = BankAccount("Asha", 1200)
acct.deposit(500)
acct.withdraw(200)
print(acct)

Check yourself

What is <code>self</code> inside a method?

If you write <code>items = []</code> in a class body, what happens?

Which method should return the string a developer sees in the console and in debuggers?

Ask the CipherCode AI tutor

Teach me object-oriented design for a small project of my choice (a school, a gym or a cinema). Ask me to list the nouns and verbs first, then guide me to turn them into classes, attributes and methods without giving me the final code until I have tried.

Next module

Module 4

OOP: inheritance and dunder methods

Reuse code with inheritance, choose composition when it fits, and make your objects behave like built-in types.

About 65 minutes

A single class is useful. A family of related classes is powerful. In this module you will learn three ideas that make classes feel like part of the language itself: inheritance (a class builds on another), polymorphism (different classes answer the same call in their own way) and dunder methods (special methods that let your objects work with +, ==, len() and sorted()).

1. Inheritance: is-a relationships

If a Latte is a kind of Drink, make Latte a subclass (child) of Drink, the superclass (parent). The child automatically gets every attribute and method of the parent, and can add new ones or replace (override) existing ones.

drinks.py
class Drink:
    def __init__(self, name, base_price):
        self.name = name
        self.base_price = base_price

    def price(self):
        return self.base_price

    def describe(self):
        return f"{self.name}: Rs {self.price()}"

class Latte(Drink):                       # Latte inherits everything from Drink
    def __init__(self, size="medium"):
        super().__init__("Latte", 180)    # run the PARENT's __init__
        self.size = size

    def price(self):                      # override: replace the parent's version
        extra = {"small": -20, "medium": 0, "large": 40}[self.size]
        return self.base_price + extra

tea = Drink("Tea", 30)
big_latte = Latte("large")

print(tea.describe())
print(big_latte.describe())               # describe() is inherited, but calls Latte.price()
print(isinstance(big_latte, Drink), isinstance(big_latte, Latte), isinstance(tea, Latte))
print(issubclass(Latte, Drink))
Notice that describe() was written only once, yet it printed the large-latte price. Inside describe, self.price() asks the actual object which version to use. That is the secret of the next section.

2. super(): calling the parent

super() gives you access to the parent class's methods from inside the child. Its most common use is inside __init__: let the parent set up what it knows about, then add your own extras. If you forget to call super().__init__(...), the parent's attributes are never created and you get an AttributeError later.

super_demo.py
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def role(self):
        return "Employee"

class Manager(Employee):
    def __init__(self, name, salary, team):
        super().__init__(name, salary)
        self.team = team

    def role(self):
        return "Manager of " + str(len(self.team)) + " (" + super().role() + ")"   # extend, not replace

class Intern(Employee):
    def __init__(self, name):
        pass                              # BUG: forgot super().__init__

m = Manager("Asha", 90000, ["Ravi", "Meena"])
print(m.role(), m.salary)

i = Intern("Kabir")
try:
    print(i.name)
except AttributeError as e:
    print("AttributeError:", e)

3. Polymorphism: one call, many behaviours

Polymorphism ("many shapes") means you can call the same method on different kinds of objects and each responds in its own way, without the caller needing to know which kind it has. This removes long if type == ... chains.

shapes.py
import math

class Shape:
    def area(self):
        raise NotImplementedError("Subclasses must implement area()")

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h
    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return math.pi * self.r ** 2

shapes = [Rectangle(3, 4), Circle(1), Rectangle(2, 2.5)]

for s in shapes:                          # the loop does not care which shape it is
    print(type(s).__name__, round(s.area(), 2))

print("Total area:", round(sum(s.area() for s in shapes), 2))

try:
    Shape().area()
except NotImplementedError as e:
    print("NotImplementedError:", e)
The base class Shape acts as a contract: every shape must provide area(). Raising NotImplementedError reminds a future programmer who forgets.

4. Composition: has-a relationships

Inheritance models is-a. Many real relationships are has-a: a car has an engine, a café has a menu. For these, store one object inside another. This is composition. A good rule of thumb is prefer composition: deep inheritance trees become rigid and confusing, while composed objects can be swapped and tested independently.

composition.py
class Menu:
    def __init__(self, items):
        self.items = items                # name -> price

    def price_of(self, name):
        return self.items[name]

class Cafe:
    def __init__(self, name, menu):
        self.name = name
        self.menu = menu                  # a Cafe HAS a Menu (not IS a Menu)

    def bill(self, *names):
        return sum(self.menu.price_of(n) for n in names)

menu = Menu({"tea": 30, "latte": 180, "samosa": 25})
cafe = Cafe("Byte Brew", menu)
print(cafe.bill("tea", "samosa", "samosa"))

5. Dunder methods: teaching objects Python's language

Methods whose names start and end with double underscores ("dunder", short for double underscore) are hooks that Python calls for you. When you write a + b, Python calls a.__add__(b). When you write len(x), it calls x.__len__(). Implement them and your own objects behave like built-ins. You rarely call dunders directly.

You writePython callsTypical meaning
a == ba.__eq__(b)equality of content
a < ba.__lt__(b)ordering (enables sorted)
a + ba.__add__(b)combine two objects
len(a)a.__len__()size
x in aa.__contains__(x)membership
a[i]a.__getitem__(i)indexing
bool(a)a.__bool__() or __len__truthiness
money.py
from functools import total_ordering

@total_ordering                      # we write __eq__ and __lt__; Python fills in <=, >, >=
class Money:
    def __init__(self, rupees):
        self.rupees = rupees

    def __repr__(self):
        return f"Money({self.rupees})"

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented     # let Python try something else, don't guess
        return self.rupees == other.rupees

    def __lt__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return self.rupees < other.rupees

    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return Money(self.rupees + other.rupees)

    def __hash__(self):               # defining __eq__ removes the default hash; restore it
        return hash(self.rupees)

a, b = Money(50), Money(120)
print(a + b)
print(a == Money(50), a < b, a >= b)
print(sorted([Money(90), Money(10), Money(55)]))
print(max(Money(3), Money(9)))
print(len({Money(5), Money(5), Money(7)}))     # equal objects with equal hashes collapse in a set

try:
    a + 5
except TypeError as e:
    print("TypeError:", e)
Returning NotImplemented (not raising an error) is the correct way to say "I do not know how to do this with that type". Python then raises a clean TypeError for you, as the last line shows.
playlist.py
class Playlist:
    def __init__(self, name, songs=None):
        self.name = name
        self.songs = list(songs or [])

    def __len__(self):
        return len(self.songs)

    def __getitem__(self, index):          # also makes the object iterable with for-loops
        return self.songs[index]

    def __contains__(self, song):
        return song in self.songs

    def __iter__(self):
        return iter(self.songs)

p = Playlist("Road trip", ["Kun Faya Kun", "Tum Hi Ho", "Kesariya"])
print(len(p), p[0], p[-1])
print("Tum Hi Ho" in p)
for song in p:
    print("-", song)
print(list(reversed(p.songs)))

6. @property, @classmethod and @staticmethod

A property lets you compute a value or validate an assignment while keeping the simple obj.name syntax. You can start with a plain attribute and add a property later without changing any code that uses it. A class method receives the class (cls) instead of an instance, and is the standard way to write alternative constructors. A static method receives neither; it is just a function that lives inside the class for organisation.

temperature.py
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius                 # goes through the setter below

    @property
    def celsius(self):                         # getter: temp.celsius
        return self._celsius

    @celsius.setter
    def celsius(self, value):                  # setter: temp.celsius = ...
        if value < -273.15:
            raise ValueError("Below absolute zero")
        self._celsius = value

    @property
    def fahrenheit(self):                      # read-only computed attribute
        return self._celsius * 9 / 5 + 32

    @classmethod
    def from_fahrenheit(cls, f):               # alternative constructor
        return cls((f - 32) * 5 / 9)

    @staticmethod
    def is_boiling(celsius):                   # no self, no cls
        return celsius >= 100

t = Temperature(25)
print(t.celsius, t.fahrenheit)
t.celsius = 100
print(t.fahrenheit, Temperature.is_boiling(t.celsius))
print(Temperature.from_fahrenheit(212).celsius)

for action in (lambda: setattr(t, "celsius", -500), lambda: setattr(t, "fahrenheit", 50)):
    try:
        action()
    except (ValueError, AttributeError) as e:
        print(type(e).__name__, "-", e)

7. Dataclasses: less boilerplate

Many classes only exist to hold a few fields. Writing __init__, __repr__ and __eq__ by hand for each is repetitive. The @dataclass decorator (standard library, since Python 3.7) writes them for you from type-annotated fields. Use field(default_factory=list) for mutable defaults, and frozen=True to make instances read-only and hashable.

dataclass_demo.py
from dataclasses import dataclass, field

@dataclass
class Expense:
    amount: float
    category: str
    note: str = ""                              # default value
    tags: list = field(default_factory=list)    # safe mutable default

    def is_big(self):
        return self.amount >= 1000

e1 = Expense(250, "food", "lunch")
e2 = Expense(250, "food", "lunch")
print(e1)                       # free __repr__
print(e1 == e2)                 # free __eq__ compares all fields
print(e1.is_big())

@dataclass(frozen=True, order=True)             # order=True: free <, > using field order
class Version:
    major: int
    minor: int

print(sorted([Version(1, 5), Version(1, 2), Version(0, 9)]))

try:
    Version(1, 0).major = 2
except Exception as e:
    print(type(e).__name__)

Remember this

  • Inheritance models is-a; the child inherits attributes and methods and can override them.
  • Call super().__init__(...) in a child so the parent can set up its own attributes.
  • Polymorphism lets one loop call the same method on different classes with no type checks.
  • Prefer composition (has-a) when the relationship is not truly is-a.
  • Dunder methods like __eq__, __lt__, __add__ and __len__ let objects work with Python operators and built-ins.
  • @property, @classmethod, @staticmethod and @dataclass remove boilerplate and add safety.

Your turn

Write a base class Employee with name, base_salary and a monthly_pay() method that returns base_salary. Create Manager (adds a bonus given at creation) that overrides monthly_pay() using super(). Add __repr__ to Employee. Finally, print the total payroll for a list that mixes both kinds.

Manager.monthly_pay can return super().monthly_pay() + self.bonus. For the total, use sum() with a generator expression calling monthly_pay() on each object, no type checking needed.

solution.py
class Employee:
    def __init__(self, name, base_salary):
        self.name = name
        self.base_salary = base_salary

    def monthly_pay(self):
        return self.base_salary

    def __repr__(self):
        return f"{type(self).__name__}({self.name!r})"

class Manager(Employee):
    def __init__(self, name, base_salary, bonus):
        super().__init__(name, base_salary)
        self.bonus = bonus

    def monthly_pay(self):
        return super().monthly_pay() + self.bonus

staff = [Employee("Ravi", 40000), Manager("Asha", 70000, 15000), Employee("Meena", 45000)]
print(staff)
print("Payroll:", sum(p.monthly_pay() for p in staff))

Check yourself

What does <code>super().__init__(name)</code> do inside a child class?

You define <code>__eq__</code> on a class and suddenly its objects cannot be put in a set. Why?

Which relationship is best modelled with composition?

Ask the CipherCode AI tutor

Give me a short design problem (like a ride-sharing app or a school system) and ask me to decide where inheritance and where composition fits. After I answer, critique my choices and show me which dunder methods would make my classes feel natural to use.

Next module

Module 5

Errors, files and JSON

Fail on purpose with custom exceptions, then read and write files, JSON and CSV safely with pathlib and logging.

About 60 minutes

Real programs meet messy situations: a file that is missing, a user who types letters where a number should be, a saved file that got corrupted. A beginner program crashes. An intermediate program expects these situations, reports them clearly and either recovers or stops cleanly. This module covers the three skills you need for that: designing your own errors, working with files and structured data, and leaving a trail of logs.

1. Exceptions: a quick, deeper recap

An exception is an object that Python raises when something goes wrong. It travels up through the functions that called each other until some except block catches it, or until it reaches the top and the program stops with a traceback. The full structure has four parts:

try_structure.py
def read_number(text):
    try:
        value = int(text)             # the risky step
    except ValueError:                # runs only if int() raised ValueError
        print(f"'{text}' is not a whole number")
        return None
    else:                             # runs only if NO exception happened
        print(f"parsed {value}")
        return value
    finally:                          # ALWAYS runs: cleanup goes here
        print("done with", repr(text))

read_number("42")
read_number("4two")
Catch the narrowest exception you can handle. A bare except: or except Exception: hides bugs, because it also catches typos and mistakes you did not predict.

2. Raising exceptions and writing custom ones

You can raise errors yourself with raise. This is how a function says "the input you gave me makes no sense". For your own domain, create a custom exception by subclassing Exception. A good name describes the problem (InsufficientFundsError), and a shared base class lets callers catch all errors from your module at once.

custom_errors.py
class BankError(Exception):
    """Base class for every error raised by this bank module."""

class InsufficientFundsError(BankError):
    def __init__(self, balance, requested):
        self.balance = balance
        self.requested = requested
        super().__init__(f"Cannot withdraw Rs {requested}; balance is Rs {balance}")

class InvalidAmountError(BankError):
    pass

def withdraw(balance, amount):
    if amount <= 0:
        raise InvalidAmountError("Amount must be positive")
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

for amount in (200, 5000, -10):
    try:
        print("new balance:", withdraw(1000, amount))
    except InsufficientFundsError as e:
        print("short by", e.requested - e.balance, "->", e)     # use the extra data
    except BankError as e:                                       # catches any other bank error
        print("bank problem:", e)
Python checks except clauses from top to bottom and uses the first match. Put specific exceptions before general ones, or the general one will swallow everything.

3. Exception chaining: keep the original cause

Sometimes you catch a low-level error and want to raise a more meaningful one. Use raise NewError(...) from original. Python then shows both in the traceback, with the line "The above exception was the direct cause of the following exception", and stores the original in __cause__. Without from, the traceback says "During handling of the above exception, another exception occurred", which suggests an accident rather than a deliberate translation.

chaining.py
class ConfigError(Exception):
    pass

def load_port(settings):
    try:
        return int(settings["port"])
    except KeyError as err:
        raise ConfigError("Missing 'port' in settings") from err
    except ValueError as err:
        raise ConfigError(f"Port must be a number, got {settings['port']!r}") from err

for settings in ({"port": "8080"}, {}, {"port": "eighty"}):
    try:
        print("port =", load_port(settings))
    except ConfigError as e:
        print("ConfigError:", e, "| caused by:", type(e.__cause__).__name__)

4. Files and with

A file you open must also be closed, or data may not be fully written and the operating system keeps resources tied up. The with statement guarantees closing even when an error occurs. Always use it. Open modes you need: "r" read (default), "w" write (erases the file first!), "a" append, and add encoding="utf-8" so text such as Hindi or emoji is handled the same on every computer.

5. pathlib: paths as objects

The pathlib module treats a path as an object, not a string. You join with /, test with .exists(), and read or write whole text files with one call. It works the same on Windows, macOS and Linux, so you never worry about \ versus /.

pathlib_files.py
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:      # a throwaway folder for this demo
    folder = Path(tmp) / "notes"                # build paths with /
    folder.mkdir()

    note = folder / "todo.txt"
    print(note.exists())

    note.write_text("buy milk\ncall Asha\n", encoding="utf-8")   # create/overwrite
    print(note.exists(), note.name, note.suffix, note.stem)

    # Append with the classic open()
    with open(note, "a", encoding="utf-8") as f:
        f.write("pay rent\n")

    # Read it back two ways
    print(note.read_text(encoding="utf-8").splitlines())
    with note.open(encoding="utf-8") as f:
        for number, line in enumerate(f, start=1):   # files are iterable, one line at a time
            print(number, line.rstrip())

    (folder / "a.txt").write_text("x")
    (folder / "b.csv").write_text("y")
    print(sorted(p.name for p in folder.glob("*.txt")))   # find files by pattern

    try:
        (folder / "missing.txt").read_text()
    except FileNotFoundError as e:
        print("FileNotFoundError:", type(e).__name__)
Iterating a file with for line in f reads one line at a time, so it works on files far larger than your memory. .read() loads everything at once.

6. JSON: saving structured data

JSON is a text format for structured data, and the common language of web APIs. It maps neatly to Python: objects become dictionaries, arrays become lists, strings stay strings, numbers stay numbers, true/false/null become True/False/None. The json module has four functions to remember: dumps (Python to string), loads (string to Python), dump (Python to file) and load (file to Python). The trailing s means string.

json_demo.py
import json
from pathlib import Path
import tempfile

expense = {"amount": 250.5, "category": "food", "paid": True, "tags": ["lunch", "office"], "note": None}

text = json.dumps(expense, indent=2)        # Python -> JSON text
print(text)

back = json.loads(text)                     # JSON text -> Python
print(back == expense, type(back["tags"]))

# Note: JSON object keys are always strings, and tuples become lists
print(json.dumps({1: "one"}), json.loads(json.dumps((1, 2))))

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "expenses.json"
    with open(path, "w", encoding="utf-8") as f:
        json.dump([expense, expense], f, indent=2)       # straight to a file
    with open(path, encoding="utf-8") as f:
        loaded = json.load(f)
    print(len(loaded), loaded[0]["category"])

    path.write_text("{ not valid json")
    try:
        json.loads(path.read_text())
    except json.JSONDecodeError as e:
        print("JSONDecodeError:", e.msg)

try:
    json.dumps({"when": {1, 2}})            # sets are not JSON types
except TypeError as e:
    print("TypeError:", e)

7. CSV: rows and columns

CSV (comma-separated values) stores tables. Never split lines on commas yourself: a value like "Sharma, Asha" contains a comma inside quotes. The csv module handles quoting for you. DictReader and DictWriter use the header row as keys, which makes code self-explanatory. Always open CSV files with newline="".

csv_demo.py
import csv
from pathlib import Path
import tempfile

rows = [
    {"name": "Sharma, Asha", "subject": "Maths", "marks": 88},
    {"name": "Ravi Kumar", "subject": "Science", "marks": 92},
]

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "marks.csv"

    with open(path, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["name", "subject", "marks"])
        writer.writeheader()
        writer.writerows(rows)

    print(path.read_text(encoding="utf-8"))      # see how the comma was quoted

    with open(path, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            print(row["name"], int(row["marks"]) + 5)    # values come back as strings!
Everything in a CSV is text, so convert with int() or float() before doing maths.

8. Logging basics

print() is fine for results the user should see. For messages about what the program is doing (progress, warnings, failures), use logging. You get severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), automatic timestamps if you want them, and the ability to turn noise on or off without editing code. logger.exception() inside an except block records the full traceback.

logging_demo.py
import logging
import sys

logging.basicConfig(
    stream=sys.stdout,                    # normally goes to the screen (stderr) or a file
    level=logging.INFO,                   # DEBUG messages are hidden at this level
    format="%(levelname)s | %(name)s | %(message)s",
)
log = logging.getLogger("expenses")       # one logger per module is the habit

log.debug("hidden at INFO level")
log.info("loaded %d expenses", 12)
log.warning("category %r is new", "travel")

try:
    1 / 0
except ZeroDivisionError:
    log.error("could not compute average: no expenses")

# log.exception("...") inside except also prints the traceback
Use %s-style placeholders (log.info("x=%d", x)) instead of f-strings: the string is only built if the message will actually be shown.

Remember this

  • try/except/else/finally: catch the narrowest exception, and put cleanup in finally.
  • Custom exceptions subclass Exception; a shared base class lets callers catch a whole family.
  • raise New(...) from original keeps the cause and gives clearer tracebacks.
  • Use with open(...) or pathlib; always pass encoding='utf-8' for text.
  • json.dumps/loads work on strings, json.dump/load on files; CSV values come back as strings.
  • Use logging with levels for diagnostics and print for user-facing output.

Your turn

Write load_scores(path) that reads a JSON file containing a list of numbers and returns their average. If the file is missing or contains invalid JSON, raise a custom ScoreFileError (use raise ... from). Test it with a temporary file that holds [70, 80, 90] and another that holds broken text.

Catch FileNotFoundError and json.JSONDecodeError separately, or together as a tuple. Use tempfile.TemporaryDirectory and Path.write_text to create the test files.

solution.py
import json
import tempfile
from pathlib import Path

class ScoreFileError(Exception):
    pass

def load_scores(path):
    try:
        data = json.loads(Path(path).read_text(encoding="utf-8"))
    except FileNotFoundError as err:
        raise ScoreFileError(f"No such file: {path}") from err
    except json.JSONDecodeError as err:
        raise ScoreFileError(f"{path} is not valid JSON") from err
    return sum(data) / len(data)

with tempfile.TemporaryDirectory() as tmp:
    good = Path(tmp) / "good.json"
    bad = Path(tmp) / "bad.json"
    good.write_text("[70, 80, 90]")
    bad.write_text("[70, 80,")

    print(load_scores(good))
    for p in (bad, Path(tmp) / "nope.json"):
        try:
            load_scores(p)
        except ScoreFileError as e:
            print("ScoreFileError:", type(e.__cause__).__name__)

Check yourself

Which mode erases an existing file's contents as soon as you open it?

What is the difference between <code>json.load</code> and <code>json.loads</code>?

Why write <code>raise ConfigError(...) from err</code> instead of just raising a new error?

Ask the CipherCode AI tutor

Review my approach to error handling in a small Python program. I will paste the code. Tell me which exceptions I am catching too broadly, which custom exceptions I should create, and where logging would help me debug problems later. Explain each suggestion in plain words.

Next module

Module 6

Modules, packages and environments

Split code across files, understand how imports are found, and isolate each project's tools in a virtual environment.

About 55 minutes

A 40-line script fits in one file. A 4,000-line program does not. Python's answer is simple: a file is a module, a folder of modules is a package, and you pull code from one into another with import. Alongside this, every project needs its own set of installed libraries, kept apart from other projects: that is what a virtual environment is for.

1. Modules and the different ways to import

Any file that ends in .py is a module, and its name is the file name without the extension. The standard library is full of modules (math, json, pathlib). The first time you import a module, Python runs its code once and keeps the result in memory, so importing it again elsewhere is instant and shares the same objects.

import_styles.py
import math                          # use as math.sqrt(...)
from math import sqrt, pi            # bring names in directly
import statistics as stats           # give a long name a short alias
from collections import Counter as C # alias for a single name

print(math.sqrt(49), sqrt(16), round(pi, 3))
print(stats.mean([70, 80, 90]))
print(C("banana").most_common(1))

# Every module has a __name__, and you can inspect what it offers
print(math.__name__, "sqrt" in dir(math))
print(type(math))
Prefer import module or from module import name. Avoid from module import *: it dumps unknown names into your file and can silently overwrite your own variables.

2. How Python finds modules

When you write import tools, Python searches, in order: modules already imported (the cache sys.modules), built-in modules, then each folder listed in sys.path. That list starts with the folder of the script you ran, followed by your installed packages. If nothing matches, you get ModuleNotFoundError: No module named 'tools'. The usual causes are a typo, running the script from the wrong folder, or a library you have not installed in the active environment.

3. if __name__ == "__main__"

A file can be both a module (imported by others) and a program (run directly). Python sets __name__ to "__main__" when a file is run directly, and to the module's own name when it is imported. Putting your starting code under if __name__ == "__main__": means importing the file has no side effects.

Let us prove all of this by building a real package on the fly inside a temporary folder, importing it and watching what happens.

build_a_package.py
import sys
import tempfile
import importlib
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    pkg = root / "cafekit"                       # a folder = a package
    pkg.mkdir()

    # __init__.py runs when the package is imported; it can expose a friendly API
    (pkg / "__init__.py").write_text(
        'from .pricing import add_tax\n'
        '__all__ = ["add_tax"]\n'
        'print("cafekit package loaded")\n'
    )
    (pkg / "pricing.py").write_text(
        'TAX = 0.05\n'
        'def add_tax(price):\n'
        '    return round(price * (1 + TAX), 2)\n'
        'if __name__ == "__main__":\n'
        '    print("running pricing.py directly")\n'
        'print("pricing module name:", __name__)\n'
    )

    sys.path.insert(0, str(root))                # make the folder importable
    try:
        import cafekit                           # runs __init__.py -> imports pricing
        print(cafekit.add_tax(200))              # short name exposed by __init__.py
        from cafekit.pricing import TAX
        print(TAX)

        import cafekit                           # second import: cached, nothing re-runs
        print("cafekit" in sys.modules)

        try:
            import cafekit.billing                # does not exist
        except ModuleNotFoundError as e:
            print("ModuleNotFoundError:", e)
    finally:
        sys.path.remove(str(root))
        for name in [n for n in sys.modules if n.startswith("cafekit")]:
            del sys.modules[name]
Look at the order of the printed lines: the package __init__.py runs first, which imports pricing, which prints its own name (cafekit.pricing, not __main__). The second import cafekit prints nothing because Python used its cache.

4. Packages and project layout

A package is a folder with an __init__.py file (it can be empty). Inside it you can nest more modules and sub-packages and import with dots: from cafekit.pricing import add_tax. Inside a package, a leading dot means "from this same package": from .pricing import add_tax. A tidy layout for a small project looks like this:

project layout
cafe-manager/
├── .venv/                 <- virtual environment (never commit this)
├── .gitignore
├── README.md
├── requirements.txt       <- pinned list of libraries
├── src/
│   └── cafekit/
│       ├── __init__.py
│       ├── menu.py
│       ├── pricing.py
│       └── cli.py          <- command-line entry point
└── tests/
    ├── test_menu.py
    └── test_pricing.py

5. Circular imports and how to avoid them

A circular import happens when a.py imports b.py while b.py imports a.py. Python starts loading a, pauses at the import, starts loading b, which asks for something from a that has not been defined yet, and fails with ImportError: cannot import name 'x' from partially initialized module 'a' (most likely due to a circular import).

  • Move the shared code into a third module that both import (the cleanest fix).
  • Import the module, not the name (import a instead of from a import x) and use a.x only inside functions, after loading has finished.
  • Import inside the function that needs it, as a last resort.
  • Rethink the design: two modules that need each other are usually one module in disguise.

6. Virtual environments

Imagine project A needs library version 1 and project B needs version 2. If both install into one global place, one project breaks. A virtual environment is a private folder holding its own Python interpreter link and its own installed packages. Activate it, and python and pip refer to that copy. Nothing you install affects other projects or your system Python.

terminal (macOS / Linux)
python3 -m venv .venv               # create the environment in a folder named .venv
source .venv/bin/activate           # activate it: your prompt shows (.venv)
python -m pip install requests      # installs only into this environment
python -m pip list                  # see what is installed here
deactivate                          # leave the environment
terminal (Windows PowerShell)
py -m venv .venv
.venv\Scripts\Activate.ps1          # if scripts are blocked, run: Set-ExecutionPolicy -Scope Process RemoteSigned
python -m pip install requests
deactivate
Write python -m pip rather than bare pip. It guarantees the pip belongs to the same Python you are using, which avoids the classic "I installed it but it still says not found" confusion.

You can ask Python which environment you are in. When a virtual environment is active, sys.prefix points inside it and differs from sys.base_prefix.

which_env.py
import sys

in_venv = sys.prefix != sys.base_prefix
print("Inside a virtual environment:", in_venv)
print("Python version OK:", sys.version_info >= (3, 10))
The first line prints True inside an activated venv and False outside. The output depends on how you run it, which is exactly the point.

7. requirements.txt, pip and pyproject.toml

pip freeze > requirements.txt records exactly what is installed, with versions, so a teammate (or a server) can recreate the same setup with pip install -r requirements.txt. Pin versions with == (requests==2.32.3) for repeatable builds, or use a looser range such as requests>=2.31,<3 for libraries. Modern projects describe themselves in a pyproject.toml file, a standard configuration file that holds the project name, version, Python requirement and dependencies, and that build and test tools also read.

requirements.txt
requests==2.32.3
pandas>=2.0,<3
pytest==8.3.3
pyproject.toml
[project]
name = "cafekit"
version = "0.1.0"
description = "Tools for running a small cafe"
requires-python = ">=3.10"
dependencies = ["requests>=2.31"]

[project.optional-dependencies]
dev = ["pytest>=8"]
With this file in place, python -m pip install -e . installs your own project in editable mode, so import cafekit works from anywhere in the environment and edits show up immediately.

8. pipx: installing command-line tools

Some Python packages are not libraries you import but programs you run (formatters, linters, project generators). pipx installs each such tool into its own hidden virtual environment and puts the command on your PATH, so tools never conflict with your projects: pipx install black then just run black . anywhere. Use pip inside a venv for libraries your code imports, and pipx for stand-alone tools.

Remember this

  • A module is a .py file; a package is a folder with __init__.py; import runs a module once and caches it.
  • Python searches sys.modules, built-ins, then sys.path (starting with the script's folder).
  • Guard script-only code with if __name__ == '__main__' so imports have no side effects.
  • Break circular imports by moving shared code into a third module.
  • Create one venv per project with python -m venv .venv, activate it, and use python -m pip.
  • Record dependencies in requirements.txt or pyproject.toml; use pipx for stand-alone command-line tools.

Your turn

In a temporary folder (as in the lesson), create a module greetings.py with a function greet(name) and a line under an if __name__ == "__main__": guard that prints "demo". Import it from code, call greet("Asha"), and show that the guarded line did not run on import.

Write the file text with Path.write_text, add the folder to sys.path, then use importlib.import_module('greetings'). The guarded print should be absent from the output.

solution.py
import importlib
import sys
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    (Path(tmp) / "greetings.py").write_text(
        'def greet(name):\n'
        '    return f"Namaste, {name}!"\n'
        'if __name__ == "__main__":\n'
        '    print("demo")\n'
    )
    sys.path.insert(0, tmp)
    try:
        greetings = importlib.import_module("greetings")
        print(greetings.greet("Asha"))
        print("module name is", greetings.__name__)
    finally:
        sys.path.remove(tmp)
        sys.modules.pop("greetings", None)

Check yourself

What does <code>if __name__ == "__main__":</code> protect against?

Which command correctly installs a library into the active virtual environment's Python?

Two modules import each other and fail with a 'partially initialized module' error. What is the cleanest fix?

Ask the CipherCode AI tutor

Help me structure a Python project called 'cafe-manager' with a src folder, tests folder, virtual environment, requirements.txt and a pyproject.toml. Ask me what the program should do, then explain why each folder and file exists, and how imports should work between the modules.

Next module

Module 7

A tour of the standard library

Python ships with batteries included: learn collections, datetime, re, random, os/sys, functools and argparse before reaching for a package.

About 60 minutes

Python's slogan is "batteries included". The standard library is the large set of modules that installs with Python itself: no pip install needed, always available, well tested and documented. Before you write a helper function or add a dependency, spend thirty seconds asking whether the standard library already does it. This module tours the pieces you will use most. The goal is not to memorise everything but to know what exists, so you can look it up.

1. collections: smarter containers

The built-in list, dict and tuple cover most needs. collections adds four specialised versions that remove a lot of boilerplate.

ToolUse it when you want toReplaces
Countercount how often things appeara dict plus if key in d checks
defaultdictgroup items; missing keys start with a defaultd.setdefault(...) or if key not in d
dequeadd/remove quickly at both ends (queues)list.pop(0), which is slow
namedtuplea light record with named fieldsplain tuples with magic indexes
collections_tour.py
from collections import Counter, defaultdict, deque, namedtuple

# Counter: tally things
orders = ["tea", "latte", "tea", "mocha", "tea", "latte"]
tally = Counter(orders)
print(tally)
print(tally.most_common(2))              # top two
print(tally["espresso"])                 # missing key gives 0, not an error

# defaultdict: group without checking whether the key exists
by_table = defaultdict(list)             # list() is called for any missing key
for table, item in [(1, "tea"), (2, "latte"), (1, "samosa"), (2, "tea")]:
    by_table[table].append(item)
print(dict(by_table))

# deque: a queue where both ends are fast
queue = deque(["Asha", "Ravi"])
queue.append("Meena")                    # join the back
print(queue.popleft(), list(queue))      # serve the front
recent = deque(maxlen=3)                 # keeps only the 3 latest items
for n in range(1, 6):
    recent.append(n)
print(list(recent))

# namedtuple: tuple with names
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p, p.x, p[1])
x, y = p                                 # still unpacks like a tuple
print(x + y)
Pick defaultdict(list) to group, defaultdict(int) to count, and Counter when counting is the whole job. For records you plan to extend with methods, a @dataclass is usually better than a namedtuple.

2. datetime: dates, times and durations

Dates look simple until you meet month lengths, leap years and time zones. The datetime module gives you four main types: date (a calendar day), time, datetime (both) and timedelta (a length of time). Subtracting two dates gives a timedelta; adding a timedelta to a date gives a new date. Use strftime to format and strptime to parse using codes such as %d (day), %m (month), %Y (4-digit year), %H:%M (24-hour time).

datetime_tour.py
from datetime import date, datetime, timedelta, timezone

due = date(2026, 3, 15)
borrowed = date(2026, 2, 20)

gap = due - borrowed                       # date - date = timedelta
print(gap.days, "days")
print(borrowed + timedelta(days=14))       # date + timedelta = date
print(due.weekday(), due.strftime("%A, %d %B %Y"))    # 0 = Monday

# Parse text into a datetime, then format it differently
when = datetime.strptime("25/10/2026 18:45", "%d/%m/%Y %H:%M")
print(when)
print(when.strftime("%I:%M %p on %d %b"))
print(when + timedelta(hours=8))

# ISO format is the safest way to store dates as text
print(when.isoformat(), datetime.fromisoformat("2026-10-25T18:45:00") == when)

# Time zones: "aware" datetimes know their offset (IST is UTC+05:30)
ist = timezone(timedelta(hours=5, minutes=30))
meeting = datetime(2026, 10, 25, 9, 0, tzinfo=ist)
print(meeting.astimezone(timezone.utc))

try:
    datetime.strptime("2026-13-01", "%Y-%m-%d")
except ValueError as e:
    print("ValueError:", e)
date.today() and datetime.now() give the current moment; they are left out of the demo because their output changes every run. Store timestamps in UTC and convert to local time only when displaying.

3. re: regular expressions, the basics

A regular expression (regex) is a tiny language for describing text patterns. Use it for validating or extracting text that follows a shape: phone numbers, dates in logs, order IDs. Always write patterns as raw strings (r"...") so backslashes reach the regex engine untouched.

PatternMeaningExample match
\d, \w, \sa digit, a word character, whitespace7, a, space
.any one character (except newline)x
* + ?0 or more, 1 or more, 0 or 1 of the previous\d+ matches 2026
{n} {n,m}exactly n, or n to m times\d{4}
[abc] [^abc]one of / anything except these characters[aeiou]
^ $start / end of the text^Hello
( )capture a group to extract it(\d+)-(\d+)
re_tour.py
import re

log = "2026-10-25 ERROR order=A104 amount=250; 2026-10-26 INFO order=B220 amount=1200"

# findall: every match as a list
print(re.findall(r"order=([A-Z]\d+)", log))             # the (...) group is returned

# search: first match anywhere; returns a Match object or None
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", log)
if m:                                                    # ALWAYS check for None
    print(m.group(0), m.group(1), m.groups())

# match checks only the START; fullmatch must match everything
print(bool(re.match(r"\d+", "123abc")), bool(re.fullmatch(r"\d+", "123abc")))

# validate an Indian mobile number: starts with 6-9, then 9 more digits
phone = re.compile(r"[6-9]\d{9}")                        # compile once if reused
for number in ("9876543210", "1234567890", "98765"):
    print(number, bool(phone.fullmatch(number)))

# sub: replace by pattern; split on pattern
print(re.sub(r"\d+", "#", "room 12, floor 3"))
print(re.split(r"[,;]\s*", "tea, coffee;milk,  juice"))

# named groups make results self-explanatory
pattern = r"order=(?P<id>\w+) amount=(?P<amount>\d+)"
for found in re.finditer(pattern, log):
    print(found["id"], int(found["amount"]))
re.search(...).group() on a failed search crashes with AttributeError: 'NoneType' object has no attribute 'group'. Test the result with if m: first.

4. random: controlled chance

random produces pseudo-random numbers: they look random but follow a formula started from a seed. Setting the seed makes a run repeatable, which is valuable for tests and demos. Never use random for passwords or security tokens; use the secrets module for that.

random_tour.py
import random

rng = random.Random(2026)                    # own generator with a fixed seed: repeatable

dice = rng.randint(1, 6)                     # both ends included
print(1 <= dice <= 6)

menu = ["tea", "latte", "mocha", "espresso"]
print(rng.choice(menu) in menu)              # one random item

picked = rng.sample(menu, k=2)               # two DIFFERENT items
print(len(picked) == len(set(picked)))

deck = list(range(10))
rng.shuffle(deck)                            # shuffles IN PLACE and returns None
print(sorted(deck) == list(range(10)))

# Same seed, same sequence - that is what makes tests repeatable
a = random.Random(7)
b = random.Random(7)
print([a.randint(1, 100) for _ in range(5)] == [b.randint(1, 100) for _ in range(5)])
The demo prints checks about the results instead of the raw values, because the exact numbers could differ between Python versions. Run it yourself and print the values to see the shapes.

5. os, sys and platform details

os talks to the operating system: environment variables, the current folder, listing files. sys talks to the Python interpreter: the version, the command-line arguments (sys.argv) and how to exit. For file paths, prefer pathlib; for configuration such as secrets and API keys, prefer environment variables over hard-coding values in source files.

os_sys_tour.py
import os
import sys
from pathlib import Path

print(sys.version_info >= (3, 10))            # tuple comparison against a version
print(type(sys.argv), len(sys.argv) >= 1)     # sys.argv[0] is the script name
print(os.name in ("posix", "nt"))

# Environment variables: the right place for secrets and settings
os.environ["CAFE_MODE"] = "demo"              # set one for this process only
print(os.environ.get("CAFE_MODE"))
print(os.environ.get("DEFINITELY_NOT_SET", "fallback"))   # .get avoids KeyError

print(Path.cwd().is_absolute())               # current working directory
print(os.path.join("data", "menu.json"))      # old-style path join (pathlib's / is nicer)
print(os.cpu_count() >= 1)

if len(sys.argv) > 5:
    sys.exit("Too many arguments")            # prints message to stderr, exits with status 1

6. functools: tools for functions

functools has three tools worth knowing now. lru_cache remembers results so an expensive function with the same inputs runs only once (memoisation). partial pre-fills some arguments of a function to make a simpler one. reduce folds a sequence into a single value. Also, wraps is used when you write decorators so your wrapped function keeps its name and docstring.

functools_tour.py
from functools import lru_cache, partial, reduce, wraps

# lru_cache: huge speed-up for repeated sub-problems
@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))                       # instant; the naive version would take ages
print(fib.cache_info().hits > 0)

# partial: fix some arguments in advance
def price_with_tax(price, rate):
    return round(price * (1 + rate), 2)

gst18 = partial(price_with_tax, rate=0.18)
print(gst18(1000), gst18(250))

# reduce: combine items left to right
print(reduce(lambda total, n: total * n, [1, 2, 3, 4, 5]))

# wraps: a decorator that keeps the original function's identity
def shout(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name):
    """Greet someone."""
    return f"hello {name}"

print(greet("asha"), greet.__name__, greet.__doc__)
You have now seen a decorator: @shout is shorthand for greet = shout(greet). It is a closure from the functions module doing real work.

7. argparse: command-line programs

Instead of editing the script every time you want a different input, let users pass options on the command line, like python cafe.py add latte --qty 2. argparse defines the arguments, converts types, shows --help automatically and prints a clear error when something is wrong. Normally parse_args() reads sys.argv; passing a list is a handy way to test it.

cafe_cli.py
import argparse

def build_parser():
    parser = argparse.ArgumentParser(prog="cafe", description="Tiny cafe order tool")
    sub = parser.add_subparsers(dest="command", required=True)

    add = sub.add_parser("add", help="add an item to the order")
    add.add_argument("item", help="name of the drink")                    # positional
    add.add_argument("--qty", type=int, default=1, help="how many")        # optional, typed
    add.add_argument("--size", choices=["small", "medium", "large"], default="medium")

    sub.add_parser("bill", help="print the bill")
    return parser

parser = build_parser()

args = parser.parse_args(["add", "latte", "--qty", "2", "--size", "large"])
print(args.command, args.item, args.qty, args.size)
print(parser.parse_args(["bill"]))

# Errors are reported by argparse and exit the program (SystemExit), so we catch it here
import contextlib, io
for bad in (["add"], ["add", "tea", "--qty", "two"], ["add", "tea", "--size", "huge"]):
    err = io.StringIO()
    with contextlib.redirect_stderr(err), contextlib.suppress(SystemExit):
        parser.parse_args(bad)
    print(err.getvalue().strip().splitlines()[-1])
In a real script you would finish with args = build_parser().parse_args() inside if __name__ == "__main__":. Run python cafe_cli.py --help to see the free documentation.

Remember this

  • Counter counts, defaultdict groups, deque makes fast queues, namedtuple makes light records.
  • datetime subtraction gives a timedelta; use strptime/strftime for text, and avoid mixing naive and aware datetimes.
  • Write regex as raw strings, check re.search results for None, and use named groups for readability.
  • Seed random.Random(seed) for repeatable runs; use secrets for anything security-related.
  • Keep secrets in environment variables read with os.environ.get, not in source code.
  • functools.lru_cache, partial and wraps solve common function problems; argparse builds command-line tools with free --help.

Your turn

Given the text "the cat saw the dog and the cat ran", use Counter to print the three most common words and their counts. Then use defaultdict(list) to group the words by their first letter, and print the groups with sorted keys.

text.split() gives the words. Counter(words).most_common(3) handles part one. For part two, append each word to by_letter[word[0]].

solution.py
from collections import Counter, defaultdict

text = "the cat saw the dog and the cat ran"
words = text.split()

print(Counter(words).most_common(3))

by_letter = defaultdict(list)
for w in words:
    by_letter[w[0]].append(w)

for letter in sorted(by_letter):
    print(letter, by_letter[letter])

Check yourself

Which collections tool is best for building a dictionary that maps each table number to a list of ordered items?

Why should regular expression patterns be written as raw strings like <code>r"\d+"</code>?

What does <code>@lru_cache</code> do?

Ask the CipherCode AI tutor

I want to practise the Python standard library. Give me five small real-world tasks (log parsing, scheduling, counting, command-line tools, caching) where I must choose the right module myself. After each answer, tell me whether a simpler standard-library tool existed and explain why.

Next module

Module 8

APIs and data with NumPy and pandas

Fetch data from web APIs, turn JSON and CSV into Python objects, then analyse numbers quickly with NumPy and pandas.

About 55 minutes

Most useful programs do not invent their own data. They ask another program for it: today's weather, a cricket score, a payment status, a list of books. The standard way for programs to talk to each other over the internet is an API (application programming interface). In this module you will call a web API, read the JSON that comes back, load tabular data from CSV files, and then use NumPy and pandas to analyse it. These are the same steps behind almost every data and AI project.

1. What an HTTP API really is

A web API is a conversation in two parts. Your program sends a request to a URL. The server sends back a response. A request has a method (GET to read data, POST to create it, PUT or PATCH to change it, DELETE to remove it), a URL, optional query parameters after the ?, and optional headers such as your login token. A response has a status code, headers and a body. The body is usually JSON, a text format that looks like Python dictionaries and lists.

Status codeMeaningWhat your program should do
200OK, here is your dataread the body
201Created (after a POST)read the new item from the body
400Bad request: you sent something invalidfix the parameters; do not retry blindly
401 / 403Not logged in / not allowedcheck your API key or permissions
404That item does not existhandle it as 'not found'
429Too many requests (rate limit)wait, then try again more slowly
500 and aboveThe server has a problemretry later; it is not your bug

Python's standard library can make requests, but almost everyone uses the third-party package requests because it is far easier to read. Install it inside your virtual environment with pip install requests. The examples below call a made-up cafe API at api.example.com, so the output is shown as it would appear when the server answers.

get_menu.py
import requests

URL = "https://api.example.com/menu"

response = requests.get(
    URL,
    params={"category": "coffee", "limit": 3},      # becomes ?category=coffee&limit=3
    headers={"Accept": "application/json"},
    timeout=5,                                      # seconds; ALWAYS set one
)

print(response.status_code)
print(response.url)
data = response.json()                              # parse the JSON body into Python objects
for item in data["items"]:
    print(item["name"], "-", item["price"])
params= builds and encodes the query string for you, so you never glue strings together by hand. response.url shows the final address that was requested.

Walk through it line by line. requests.get(...) sends the request and waits for the reply. timeout=5 tells it to give up after five seconds instead of waiting forever. response.status_code is the number from the table above. response.json() converts the JSON text into a Python dictionary, so data["items"] is a list of dictionaries and you can loop over it like any other list.

2. Handling failure properly

Networks fail: Wi-Fi drops, servers restart, you pass a wrong ID. Wrap the call in try/except and use response.raise_for_status(), which turns any 4xx or 5xx status into an HTTPError. Catch the specific problems you can handle and let unknown bugs crash loudly.

safe_fetch.py
import os
import requests

# Never hardcode secrets. Read the key from an environment variable.
API_KEY = os.environ.get("CAFE_API_KEY", "")

def get_item(item_id):
    url = f"https://api.example.com/menu/{item_id}"
    try:
        response = requests.get(url, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=5)
        response.raise_for_status()                 # 4xx / 5xx -> HTTPError
        return response.json()
    except requests.exceptions.Timeout:
        print("The server took too long. Try again.")
    except requests.exceptions.ConnectionError:
        print("Could not reach the server. Check your internet.")
    except requests.exceptions.HTTPError as err:
        print("Server said no:", err)
    return None

print(get_item(2))
print(get_item(99))
Put the key in your terminal first: export CAFE_API_KEY=abc123 on macOS and Linux, or setx CAFE_API_KEY abc123 on Windows. Never commit keys to Git.

3. Turning JSON text into Python objects

JSON maps neatly onto Python: objects become dict, arrays become list, strings become str, numbers become int or float, true/false become True/False and null becomes None. response.json() does this for web responses. For text you already have, use json.loads (load string) and json.dumps to go back. Real responses are often nested, so use .get() with a default when a key might be missing.

parse_json.py
import json

body = """
{
  "match": "Lions vs Tigers",
  "completed": true,
  "players": [
    {"name": "Asha", "runs": 52, "team": "Lions"},
    {"name": "Ravi", "runs": 34, "team": "Tigers"},
    {"name": "Meena", "runs": 78, "team": "Lions", "notes": null}
  ]
}
"""
data = json.loads(body)                          # text -> dict
print(type(data).__name__, data["completed"])

for p in data["players"]:
    # .get() avoids KeyError when "notes" is missing; the default covers null too
    note = p.get("notes") or "no notes"
    print(f'{p["name"]:<6} {p["runs"]:>3}  {note}')

lions_total = sum(p["runs"] for p in data["players"] if p["team"] == "Lions")
print("Lions total:", lions_total)

# back to text: indent makes it readable, sort_keys makes it predictable
summary = {"top": max(data["players"], key=lambda p: p["runs"])["name"], "total": lions_total}
print(json.dumps(summary, indent=2, sort_keys=True))

try:
    json.loads("{'bad': 'quotes'}")
except json.JSONDecodeError as e:
    print("JSONDecodeError:", e)
JSON needs double quotes. Python-style single quotes fail with JSONDecodeError: Expecting property name enclosed in double quotes.

4. Tables from text: the csv module

A CSV (comma-separated values) file is the simplest table format: one row per line, columns separated by commas. Spreadsheets export it and APIs often provide it. Use csv.DictReader, which reads each row as a dictionary keyed by the header row, so your code uses column names instead of fragile positions. Everything arrives as a string, so convert numbers yourself. The demo reads from an in-memory text with io.StringIO; with a real file you would write open("expenses.csv", newline="", encoding="utf-8") instead.

read_csv.py
import csv
import io
from collections import defaultdict

text = """date,category,amount
2026-10-01,food,250
2026-10-02,travel,120
2026-10-03,food,340.50
2026-10-04,books,899
2026-10-05,travel,80
"""

totals = defaultdict(float)
with io.StringIO(text) as f:                       # stand-in for open("expenses.csv", newline="")
    for row in csv.DictReader(f):
        totals[row["category"]] += float(row["amount"])   # strings -> numbers

for category, amount in sorted(totals.items(), key=lambda kv: kv[1], reverse=True):
    print(f"{category:<8} {amount:>8.2f}")

# writing CSV back out
out = io.StringIO()
writer = csv.writer(out)
writer.writerow(["category", "total"])
writer.writerows(sorted(totals.items()))
print(out.getvalue().strip())

5. NumPy: fast maths on whole arrays

A Python list can hold anything, which makes it flexible but slow for maths. NumPy (pip install numpy) provides the array: a grid of numbers that all share one type and live in a compact block of memory. The big idea is vectorisation: instead of writing a loop, you apply an operation to the whole array at once, and NumPy runs the loop in fast compiled code. Comparisons give an array of True/False called a mask, and indexing with a mask filters the data.

numpy_basics.py
import numpy as np

runs = np.array([52, 34, 78, 12, 91, 45])

print(runs.mean())                 # average of every element
print(runs.max(), runs.min())
print(runs * 2)                    # works on every element at once, no loop
print(runs[runs >= 50])            # filter with a True/False mask
print(runs.shape, runs.dtype)

grid = np.arange(1, 7).reshape(2, 3)
print(grid)
print(grid.sum(axis=0))            # add down each column
The data type may print as int32 on some Windows installations; that does not change how the code works. axis=0 means 'down the rows', axis=1 means 'across the columns'.

6. pandas: spreadsheets in code

pandas (pip install pandas) builds on NumPy and adds the DataFrame: a table with named columns and an index, like a spreadsheet you control with code. The five moves you will use constantly are: read_csv to load, head to peek, a boolean filter to select rows, a new column from arithmetic, and groupby to summarise by category. describe() gives instant statistics for a numeric column.

pandas_basics.py
import io
import pandas as pd

csv_text = """batter,team,runs,balls
Asha,Lions,52,40
Ravi,Tigers,34,30
Meena,Lions,78,55
Kiran,Tigers,12,15
Dev,Lions,91,60
Isha,Tigers,45,38
"""
df = pd.read_csv(io.StringIO(csv_text))        # in real life: pd.read_csv("scores.csv")

print(df.head(3))                              # first 3 rows
print(df.shape)                                # (rows, columns)
print(df[df["runs"] >= 50])                    # keep rows where the test is True
df["strike_rate"] = (df["runs"] / df["balls"] * 100).round(1)   # new column, no loop
print(df[["batter", "strike_rate"]])           # pick columns with a list
print(df.groupby("team")["runs"].sum())        # total per team
print(df["runs"].describe())                   # count, mean, spread, quartiles
Output shown from pandas 3. Older versions print the same numbers; small cosmetic details such as column dtype labels can differ.

Remember this

  • An API request has a method, URL, parameters and headers; the response has a status code and usually a JSON body.
  • Always pass timeout= to requests, call raise_for_status(), and catch specific exceptions such as Timeout and HTTPError.
  • Keep API keys in environment variables, never in your source code or Git history.
  • json.loads turns text into dicts and lists; use .get() for keys that may be missing.
  • csv.DictReader gives rows as dictionaries, but every value is a string until you convert it.
  • NumPy applies maths to whole arrays at once; pandas adds named columns, filters and groupby for table-shaped data.

Your turn

The text below is a tiny API response. Parse it with json.loads, then print each book title with its price, and finally print the total price of all books that are in stock. Expected total: 1050.
[{"title": "Python Basics", "price": 400, "in_stock": true}, {"title": "Data Tricks", "price": 650, "in_stock": true}, {"title": "Old Edition", "price": 300, "in_stock": false}]

json.loads gives a list of dicts. Loop to print title and price. Then sum(b["price"] for b in books if b["in_stock"]) adds only the books marked True.

solution.py
import json

body = '[{"title": "Python Basics", "price": 400, "in_stock": true}, {"title": "Data Tricks", "price": 650, "in_stock": true}, {"title": "Old Edition", "price": 300, "in_stock": false}]'
books = json.loads(body)

for b in books:
    print(b["title"], b["price"])

in_stock_total = sum(b["price"] for b in books if b["in_stock"])
print("In stock total:", in_stock_total)

Check yourself

A server replies with status code 404. What does <code>requests.get(url)</code> do by default?

Why is hardcoding an API key inside your script a bad idea?

In pandas, which expression keeps only rows where runs is at least 50 AND balls is under 60?

Ask the CipherCode AI tutor

I am learning to work with web APIs and data in Python. Give me a free public JSON API I can practise with, then walk me step by step through calling it with requests (with timeout and error handling), loading the result into a pandas DataFrame, filtering it and summarising it with groupby. Ask me to predict each output before you reveal it.

Next module

Module 9

Testing and debugging

Read tracebacks calmly, find bugs with logging and the debugger, and write automated tests that tell you when code breaks.

About 55 minutes

Every programmer writes bugs. What separates a beginner from a confident developer is not writing fewer bugs, it is finding them quickly and making sure they never come back. This module gives you both skills: a method for debugging, and automated tests that check your code every time you change it. You will also learn the Git basics that let you experiment safely.

1. Reading a traceback

When Python crashes it prints a traceback: the chain of function calls that led to the error. Beginners often panic and read it from the top. Read it from the bottom instead. The last line names the exception type and the message. The line above it shows exactly which line of code failed. Everything above that is the path Python took to get there.

traceback_demo.py
def average(marks):
    return sum(marks) / len(marks)

def report(student, marks):
    avg = average(marks)
    return f"{student}: {avg:.1f}"

print(report("Asha", [78, 91, 85]))
print(report("Ravi", []))
Bottom line first: ZeroDivisionError. Line above: len(marks) was 0 because Ravi's list is empty. The lines above show who called whom: module, then report, then average.

The bug is not really in average. It is a missing decision: what should happen when there are no marks? The traceback tells you where Python noticed the problem. You still have to work out why the data was like that. Always ask: what value did I expect here, and what value did I get?

Error you seeUsual causeFirst thing to check
NameErrorTypo or variable used before it existsSpelling and the order of your lines
TypeErrorWrong kind of value, e.g. "5" + 3Print type(value)
KeyErrorDictionary key is missingPrint the dictionary's keys
IndexErrorList position is too largePrint len(your_list)
AttributeErrorObject has no such method, often NoneWhich variable is None?

2. A method for finding bugs

  1. Reproduce it. Find the smallest input that makes the bug happen every time.
  2. Read the error from the bottom up and note the file and line.
  3. Form a guess about what is wrong: "I think marks is empty here."
  4. Test the guess by printing, logging or using the debugger. Do not just change code and hope.
  5. Fix it, then add a test so the same bug cannot return unnoticed.

3. print, logging and the debugger

print is the quickest way to look inside a program, and it is fine for a five-minute bug. Its weakness is that you must delete every print afterwards, and it cannot be turned down or sent to a file. The logging module solves this. Each message has a level (DEBUG, INFO, WARNING, ERROR, CRITICAL), and you choose which levels appear without touching the code.

logging_demo.py
import logging
import sys

logging.basicConfig(
    stream=sys.stdout,
    level=logging.INFO,                       # change to DEBUG to see more
    format="%(levelname)s | %(name)s | %(message)s",
)
log = logging.getLogger("billing")

def total(prices, discount):
    log.debug("prices=%s discount=%s", prices, discount)   # hidden at INFO level
    subtotal = sum(prices)
    if discount > 0.5:
        log.warning("discount %.0f%% is unusually high", discount * 100)
    result = subtotal * (1 - discount)
    log.info("total computed: %.2f", result)
    return result

total([120, 80, 50], 0.1)
total([120, 80, 50], 0.7)
Use %s style arguments rather than f-strings in log calls. Python only builds the message if that level is switched on, which saves work.

Sometimes you need to stop the program and look around. That is what a debugger does. Write breakpoint() on the line where you want to pause, run the script normally, and Python opens the pdb prompt right there. VS Code also lets you click beside a line number to set a breakpoint and use the Debug button.

pdb_session.txt
# In your script, add this line just before the suspicious code:
#     breakpoint()
#
# Then run:  python traceback_demo.py
# You will see a (Pdb) prompt. Useful commands:
#   p marks        print a value
#   pp data        pretty-print a big value
#   n              run the next line
#   s              step into a function call
#   c              continue until the next breakpoint
#   l              list the code around the current line
#   q              quit
The p marks answer, an empty list, confirms the guess from the traceback in one step.

4. assert: checking your own assumptions

An assert statement says "this must be true here". If it is false, Python raises AssertionError immediately and stops, close to the real mistake instead of ten lines later. Use asserts for things that would be your bug if wrong, such as internal rules. Do not use them to check user input, because Python can run with asserts switched off (python -O).

assert_demo.py
def apply_discount(price, percent):
    assert 0 <= percent <= 100, f"percent must be 0-100, got {percent}"
    return price * (100 - percent) / 100

print(apply_discount(500, 20))
try:
    print(apply_discount(500, 120))
except AssertionError as err:
    print("caught:", err)

5. Automated tests: the test-driven mindset

Debugging by hand is slow, and it only checks what you thought to try today. An automated test is a small function that calls your code with known input and checks the result. You run all tests in seconds after every change, so you find out immediately if something broke. Good tests follow Arrange, Act, Assert: set up the data, call the code, check the outcome.

Test-driven development (TDD) flips the order: write a failing test first, write the smallest code that makes it pass, then tidy up. Even if you do not follow it strictly, thinking "how would I test this?" before you write a function usually gives you smaller, clearer functions.

Python ships with unittest in the standard library. Each test is a method whose name starts with test, and you check results with methods such as assertEqual and assertRaises.

test_cart.py
import io
import unittest

def cart_total(items, discount=0.0):
    """items is a list of (name, price, quantity) tuples."""
    if not 0 <= discount < 1:
        raise ValueError("discount must be from 0 up to (not including) 1")
    subtotal = sum(price * qty for _, price, qty in items)
    return round(subtotal * (1 - discount), 2)

class CartTotalTests(unittest.TestCase):
    def test_adds_up_prices_times_quantity(self):
        # Arrange
        items = [("tea", 20, 3), ("samosa", 15, 2)]
        # Act
        result = cart_total(items)
        # Assert
        self.assertEqual(result, 90)

    def test_applies_discount(self):
        self.assertEqual(cart_total([("book", 200, 1)], discount=0.25), 150.0)

    def test_empty_cart_is_zero(self):
        self.assertEqual(cart_total([]), 0)

    def test_rejects_bad_discount(self):
        with self.assertRaises(ValueError):
            cart_total([("tea", 20, 1)], discount=1.5)

suite = unittest.defaultTestLoader.loadTestsFromTestCase(CartTotalTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)   # quiet runner
print("tests run:", result.testsRun)
print("failures:", len(result.failures), "errors:", len(result.errors))
print("all passed:", result.wasSuccessful())
In a real project you save this as test_cart.py and run python -m unittest in the terminal. The quiet runner above just lets this page print a short summary.

Look at what these four tests cover: a normal case, a case with a discount, an edge case (empty cart) and an error case (bad discount). Edge and error cases are where most real bugs live, so test them on purpose.

6. pytest: less typing, better messages

Most professional Python projects use the third-party tool pytest (pip install pytest). You write plain functions and plain assert statements, and pytest rewrites the assertion so a failure shows exactly what each side contained. It also provides fixtures (reusable setup code) and parametrize (run one test with many inputs).

test_cart_pytest.py
import pytest
from cart import cart_total

@pytest.fixture
def cafe_order():
    """A fixture: pytest builds this fresh for every test that asks for it."""
    return [("tea", 20, 3), ("samosa", 15, 2)]

def test_total_without_discount(cafe_order):
    assert cart_total(cafe_order) == 90

@pytest.mark.parametrize("discount, expected", [
    (0.0, 90.0),
    (0.1, 81.0),
    (0.5, 45.0),
])
def test_discounts(cafe_order, discount, expected):
    assert cart_total(cafe_order, discount) == expected

def test_bad_discount_raises():
    with pytest.raises(ValueError):
        cart_total([("tea", 20, 1)], discount=2)
Run it with pytest in the terminal. parametrize turns three input rows into three separate tests, so one failing row does not hide the others.

When a test fails, pytest shows you what went wrong. Suppose someone changed the discount formula by mistake:

failing_run.txt
# After a mistaken edit, running pytest prints something like this
The message names the failing case ([0.1-81.0]), the value you got (89.0) and the value you expected (81.0). That is most of the debugging done for you.

7. Git basics: a safety net for experiments

Git records snapshots of your project, called commits, so you can go back if an experiment goes wrong and work on ideas without disturbing working code. Think of a commit as a save point in a game, with a message that explains what changed. A branch is a separate line of work: you try a risky change on a branch and merge it back only when the tests pass.

git_basics.sh
git init                          # start tracking this folder
git add cart.py test_cart.py      # choose what goes into the next snapshot
git commit -m "Add cart_total with tests"

git switch -c discount-rules      # create and move to a new branch
# ... edit files, run the tests ...
git add cart.py
git commit -m "Reject discounts of 100% or more"

git switch main                   # go back to the stable branch
git merge discount-rules          # bring the finished work in
git log --oneline                 # see the history
Your commit hashes (the letters and digits) and folder path will differ. Run git status any time to see what has changed. Put .venv/ and __pycache__/ in a .gitignore file so they are never committed.

Remember this

  • Read tracebacks from the bottom: error type and message first, then the failing line, then the call path.
  • Reproduce, guess, test the guess, fix, then add a test. Never change code at random.
  • Use logging with levels for anything you want to keep, and breakpoint() to inspect a program mid-run.
  • Write tests as Arrange, Act, Assert, and always cover edge cases and error cases.
  • pytest fixtures and parametrize remove repeated setup and repeated tests.
  • Commit small, branch for experiments, and merge only when the tests pass.

Your turn

Write a function is_valid_marks(marks) that returns True when every mark in the list is a number from 0 to 100 and the list is not empty, otherwise False. Then write four unittest tests for it: a normal list, an empty list, a list with 101, and a list with a negative number. Print how many tests ran and whether all passed.

Use <code>all(...)</code> with a generator expression for the range check, and return <code>False</code> early for an empty list. In the tests use <code>assertTrue</code> and <code>assertFalse</code>.

solution.py
import io
import unittest

def is_valid_marks(marks):
    if not marks:
        return False
    return all(0 <= m <= 100 for m in marks)

class MarksTests(unittest.TestCase):
    def test_normal_list(self):
        self.assertTrue(is_valid_marks([78, 91, 85]))

    def test_empty_list(self):
        self.assertFalse(is_valid_marks([]))

    def test_mark_above_100(self):
        self.assertFalse(is_valid_marks([90, 101]))

    def test_negative_mark(self):
        self.assertFalse(is_valid_marks([50, -1]))

suite = unittest.defaultTestLoader.loadTestsFromTestCase(MarksTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("tests run:", result.testsRun)
print("all passed:", result.wasSuccessful())

Check yourself

A traceback ends with the line <code>KeyError: 'email'</code>. What is the best first step?

Why should you not use <code>assert</code> to validate data typed by a user?

In Arrange, Act, Assert, what happens in the Act step?

Ask the CipherCode AI tutor

I am learning Python testing and debugging. Here is a function of mine and the traceback it produces: [paste both]. Explain the error line by line, tell me what to check first, then help me write three pytest tests, including one edge case, without giving me the final fix until I have tried.

Build these to lock it in

Reading is not enough. Each project uses what you just learned, so build them without copying.

easy

Café order manager

A command-line program that takes orders, applies discounts and prints a bill using functions and dictionaries.

  • Functions
  • Dictionaries
  • Closures
  • Type hints
Build plan
  1. Store the menu as a dictionary of item name to price.
  2. Write add_to_order(order, item, quantity=1) without using a mutable default.
  3. Create discount strategies (student, festival) as functions kept in a dictionary.
  4. Print a formatted bill with subtotal, discount, tax and total.
  5. Add type hints and docstrings to every function.

medium

Expense tracker with JSON storage

An object-oriented tracker that saves expenses to a JSON file and reports spending by category.

  • Classes
  • Dataclasses
  • JSON and pathlib
  • Custom exceptions
Build plan
  1. Create an Expense dataclass with amount, category, note and date.
  2. Build an ExpenseBook class that adds, removes and totals expenses.
  3. Save and load the book as JSON with pathlib; raise a custom StorageError on bad files.
  4. Use Counter or defaultdict to report totals per category.
  5. Add an argparse interface: add, list and summary commands.
  6. Write at least six pytest tests.

hard

Cricket stats explorer

Fetch or load match data, clean it with pandas and publish a small report of top performers.

  • APIs and CSV
  • pandas
  • Packages
  • Testing
Build plan
  1. Organise the project as a package with a virtual environment and requirements.txt.
  2. Load a CSV of match scores (or fetch JSON from an API) into a pandas DataFrame.
  3. Clean missing values and compute batting averages and strike rates.
  4. Rank the top five players and export the table to CSV.
  5. Add logging for each stage and unit tests for your calculation functions.
  6. Record your work with git commits on a feature branch.

Quick reference

Keep this open while you code.

You writeIt means
def f(a, /, b, *, c=1):a is positional-only, b is either, c is keyword-only
def f(*args, **kwargs):collect extra positional and keyword arguments
[x*x for x in nums if x > 0]list comprehension with a filter
{k: v for k, v in pairs}dictionary comprehension
for i, x in enumerate(items, 1):loop with a counter starting at 1
for a, b in zip(xs, ys):walk two sequences in step
sorted(rows, key=lambda r: r[1])sort by a chosen field
class Cafe: def __init__(self, name): ...define a class with an initialiser
class Latte(Drink):inherit from a parent class
@propertyturn a method into a read-only attribute
@dataclassgenerate __init__, __repr__ and __eq__ for a data class
raise ValueError('msg') from errraise an error and keep the original cause
Path('a') / 'b.txt'build file paths with pathlib
json.dumps(obj, indent=2)convert Python data to JSON text
python -m venv .venvcreate an isolated environment
Counter(words).most_common(3)count items and get the top three
with open(p) as f:open a file and close it automatically
pytest -qrun all tests quietly

Ready for Advanced?

Finish the projects above, then keep the momentum going.

Go to Advanced