Object-Oriented Programming in Python – Free Online Book (UCT) BSCS / BSIT

BSCS and BSIT students can read Object-Oriented Programming in Python free online. It is a set of course notes from the University of Cape Town (UCT), first written for an MSc-level IT course and now used as a general introduction to Python and object-oriented design. There is no official PDF: the book is published as a website on Read the Docs, and its source is public on GitHub.

The book works up in two steps. Chapters 1 to 8 teach Python itself: variables, selection, collections, loops, exceptions and functions. Chapters 9 and 10 then introduce classes, inheritance, composition, mix-ins and abstract classes, and the last four chapters cover packaging and testing, the standard library, tkinter GUIs and sorting with Big O. It targets Python 3 with examples from the 2013 to 2014 era, so a few of the tools it recommends have since changed.

Book Overview

CourseObject-Oriented Programming (Python) / Programming Fundamentals
Degree ProgramsBSCS, BSIT
LevelUniversity / Undergraduate (introductory to intermediate)
EditionVersion 1 (copyright 2013, 2014); the source repository still receives small fixes, latest in November 2025
AuthorsUniversity of Cape Town and individual contributors (the repository lists Adrianna Pińska, Simon Cross, Mariana Meireles, Joseph Sarpong and Erika)
CopyrightUniversity of Cape Town and individual contributors, 2013, 2014
LanguageEnglish
Total Chapters14 (numbered here in table-of-contents order; the book itself does not number them)
Programming LanguagePython 3, with notes on Python 2.7 differences
ExercisesAbout 60 exercise sets in Chapters 2 to 14, with worked answers at the end of each chapter
LicenseCreative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) — Model: Link-only
FormatFree online book (HTML on Read the Docs); no PDF or ePub download is offered; source on GitHub

Chapter List

Chapter 1: Introduction

Difficulty: Easy · Key topics: CPU, memory, algorithm, compiler and interpreter, procedural and object-oriented languages, program development steps

The opening chapter explains what a computer is before any Python appears: input, processing, memory and output, with a vending machine as the running analogy, and the CPU split into the ALU, control unit and registers. It then walks through the history of computing from the abacus and Pascal’s calculator to the four generations of electronic machines. The programming section defines an algorithm, contrasts the recipe (structured) view with the play-script (object-oriented) view, and moves from machine language to assembly to high-level languages. It ends with the four steps of building a program and a tour of procedural, functional, logic and object-oriented languages.

Key Points:

  • A computer has four kinds of components: input, processing, memory and output.
  • Primary memory (RAM) is volatile; secondary memory such as a hard disk keeps its contents when the power is off.
  • An algorithm must be finite, unambiguous, effective and must terminate.
  • Python is an interpreted language; C is compiled and gives finer control over memory.
  • Programs are built in four steps: understand the problem, find an algorithm, write the program, test it.
  • Simula (1967) was the first object-oriented language; Smalltalk (early 1980s) was the first purely object-oriented one.

Practice Tip: Write the average-of-numbers algorithm from this chapter on paper (running total, running count, stop at 0) and test it with 1, 2, 3, 4, 5 and then with a list that holds only 0. The second test exposes an edge case the first one hides.

Common Mistake: Calling any finite list of steps an algorithm. A short list that repeats forever never terminates, so it is not an algorithm.

Important Questions:

  • What four properties must an algorithm have? It must be finite, unambiguous, effective, and it must terminate.
  • What is the difference between a compiled and an interpreted language? A compiler translates the whole source into an executable file first; an interpreter reads and runs the source line by line. Python is interpreted, C is compiled.

Chapter 2: Python Basics

Difficulty: Easy · Key topics: interpreter, identifiers, indentation, print and input, files, integers, floats, strings, formatting

This chapter gets you writing Python 3. It explains the interactive interpreter, running a .py file, installing packages from PyPI and the Python 2 versus Python 3 split. It then covers the essentials of a program: keywords, identifier rules and naming conventions, indentation, case sensitivity, comments, print and input, and reading and writing files with the with statement. The rest is built-in types: integers (including // and %), floating-point numbers and scientific notation, and strings with % formatting, escape sequences, raw strings and triple quotes.

Key Points:

  • Python marks blocks with indentation, not braces, and ends a statement at the end of the line.
  • Names are case-sensitive. Classes use CamelCase, constants use CAPITAL_LETTERS, other names use lowercase_with_underscores.
  • Python is dynamically typed but strongly typed: adding a number to a string raises a type error.
  • In Python 3, / always gives a floating-point result and // always does integer division.
  • Integers have no fixed size limit; floats follow IEEE 754 and have a limited range.
  • A raw string (prefix r) keeps backslashes as written, and triple quotes allow a string over several lines.
  • Open files with the with statement so they are closed automatically.

Practice Tip: In the interpreter, compare 28 // 10, 28 / 10 and -3 // 2. The last result is -2, which shows that // rounds down, not towards zero.

Common Mistake: Expecting input() to return a number. It always returns a string, so two typed values joined with + are glued together until you convert them with int() or float().

Important Questions:

  • What are the rules for a valid identifier? It may contain only letters, digits and underscores, it may not start with a digit, and it may not be a keyword.
  • What is the difference between / and // in Python 3? / is floating-point division and // is integer division, so 28 // 10 is 2 while 28 / 10 is 2.8.

Chapter 3: Variables and Scope

Difficulty: Easy · Key topics: scope, lifetime, global and nonlocal, constants, mutable and immutable types, type conversion

Chapter 3 explains how Python names behave. It defines variables, then scope and lifetime: global, local and class-body scopes, why assignment inside a function creates a new local variable by default, and how the global and nonlocal keywords cross those boundaries. It covers constants and magic numbers, mutable versus immutable values and reading numbers with input(). The last part treats type conversion, both implicit (an integer promoted to a float) and explicit (int, float, str, bool), and closes with a worked petrol-consumption program.

Key Points:

  • Scope is where a name is visible; lifetime is how long the variable exists.
  • Assignment inside a function creates a local variable unless the name is declared global (or nonlocal for an enclosing function).
  • A local name hides a global name of the same spelling inside the function.
  • Avoid global variables; pass values into functions as parameters instead.
  • An immutable value cannot be altered, only replaced by assigning a new value to the variable.
  • Give constants a CAPITAL name instead of scattering magic numbers through the code.
  • int(), float(), str() and bool() convert explicitly; mixing int and float promotes the result to float.

Practice Tip: Define a global a = 0, then a function that assigns a = 3 and prints it. Print a after the call, then add global a inside the function and run it again to see the difference.

Common Mistake: Reading a name inside a function before assigning it in the same function. Python treats the name as local for the whole function, so the early read fails even when a global of that name exists.

Important Questions:

  • Why does the final print show 0 after a function has set a = 3? The assignment inside the function created a new local variable, so the global a was never changed.
  • What is a magic number and how do you avoid it? It is an unexplained literal such as 80 in a print statement. Give it a constant name like MAXIMUM_MARK and define it once.

Chapter 4: Selection Control Statements

Difficulty: Easy · Key topics: if, elif, else, relational operators, is versus ==, booleans, short-circuit, De Morgan, None, conditional expression

This chapter shows how to change the flow of control. It builds up if, else and elif ladders with flowcharts, compares values with the relational operators and separates value (==) from identity (is). It then covers booleans in depth: truthiness, truth tables for and, or and not, short-circuit evaluation, operator precedence and De Morgan’s laws. The closing sections introduce None, dictionary-based dispatch as a replacement for a switch statement and the conditional (ternary) expression. The exercises centre on grade calculation.

Key Points:

  • An elif ladder runs one branch; keep a final else so unexpected input is noticed.
  • Zero, empty strings and empty collections count as False; other values count as True.
  • and and or short-circuit, so x != 0 and 10 / x > 1 never divides by zero.
  • Python allows chained comparisons such as 50 <= mark < 65.
  • De Morgan: not (a and b) equals (not a) or (not b), and not (a or b) equals (not a) and (not b).
  • None marks a variable that has no value yet, so 0 and the empty string can stay meaningful values.
  • A dictionary can stand in for a switch statement (the book predates the match statement added in Python 3.10), and a if condition else b is the conditional expression.

Practice Tip: Write the grade program from Exercise 3 and test it with 49, 50, 59, 60, 79 and 80. Each boundary value should land in a different branch of the elif ladder.

Common Mistake: Writing x == 1 or 3. The 3 is a non-zero value, so it counts as True and the whole condition is always true. Write x == 1 or x == 3. Also note that the answer to Exercise 3 still uses a Python 2 print statement and will not run in Python 3 as printed.

Important Questions:

  • What is short-circuit evaluation? Python stops evaluating a and b when a is False, and a or b when a is True, because the result is already known.
  • State De Morgan’s laws. NOT (a AND b) = (NOT a) OR (NOT b), and NOT (a OR b) = (NOT a) AND (NOT b).

Chapter 5: Collections

Difficulty: Easy · Key topics: lists, tuples, sets, ranges, dictionaries, conversions, join and split, two-dimensional lists

Chapter 5 groups values into the built-in collections. Lists get indexing, slicing, methods and the + and * operators, plus a comparison with arrays in lower-level languages. It then covers tuples, sets with union and difference style operations, ranges and dictionaries with their keys, values and items views. A section on converting between collection types includes join and split for strings. The chapter ends with two-dimensional sequences and shows why multiplying a list of lists repeats one inner list instead of copying it.

Key Points:

  • Lists are mutable and ordered; tuples are immutable sequences.
  • Sets hold unique items and support union, difference and intersection style operations; they are not ordered.
  • range(stop), range(start, stop) and range(start, stop, step) stop before the upper bound.
  • sorted(items) returns a new sorted list; items.sort() sorts the list in place.
  • A dictionary stores key-value pairs; keys(), values() and items() return read-only views, and key in mydict is the efficient membership test.
  • The book says dictionaries have no order; since Python 3.7 they remember insertion order.
  • ''.join(chars) turns a sequence of strings into one string, and split() goes the other way.

Practice Tip: Do Exercise 1 in the interpreter: build two lists, combine them, then compare sorted(c) with c.sort() to see which one returns a new list and which changes the original.

Common Mistake: Building a timetable as [day] * 7. All seven entries are the same list object, so changing one day changes every day.

Important Questions:

  • Why does one meeting appear on every day of a timetable built with list multiplication? Multiplication repeats a reference to one inner list. Build each day separately with a list comprehension.
  • How do you convert a list of characters into a string? Use ''.join(chars). Calling str() on the list gives its printed form with commas, quotes and brackets.

Chapter 6: Loop Control Statements

Difficulty: Medium · Key topics: while, for, range, enumerate, nested loops, iterators, generators, comprehensions, break, continue

Chapter 6 teaches repetition. It separates counting loops from event-controlled loops using a petrol attendant and a drive to Camps Bay as examples, then covers while loops (initialisation, condition, update) and the infinite-loop danger linked to the halting problem. The for statement is shown with range and enumerate, followed by nested loops over two-dimensional data. A longer section explains iterables, iterators and generators, then list, dict and set comprehensions. The chapter closes with break, continue, a while True loop that simulates do-while, and using loops to remove repeated code.

Key Points:

  • for suits a known number of steps; while suits repetition until a condition changes.
  • A while loop has three parts: initialisation, condition and update. Forgetting the update gives an infinite loop.
  • No program can detect every infinite loop in another program (the halting problem).
  • enumerate(items) yields (index, item) pairs, and zip stops at the shortest of its iterables.
  • A comprehension has three parts: the expression, the for clause and an optional if filter.
  • break leaves the loop, continue skips to the next iteration, and while True with break simulates a do-while loop.
  • Assigning to the loop variable does not change the list being looped over; build a new list instead.

Practice Tip: Write the sentinel exercise: ask for integers inside while True and break when the user enters a negative number, then print the average of the others.

Common Mistake: Placing continue before the line that updates the loop variable. When the value that triggers continue is reached, the update never runs and the loop repeats forever.

Important Questions:

  • What is the difference between a counting loop and an event-controlled loop? A counting loop knows its number of repeats in advance and uses for; an event-controlled loop repeats while a condition holds and uses while.
  • How do you write a loop that doubles the even numbers of a list as a comprehension? [2 * n for n in numbers if n % 2 == 0] gives the doubled even values as a new list.

Chapter 7: Errors and Exceptions

Difficulty: Medium · Key topics: syntax, runtime and logical errors, try and except, else and finally, raise, pdb, linters, logging

Chapter 7 classifies errors as syntax, runtime and logical, and explains why logical errors are the hardest to find. It then teaches exception handling: try and except with a named exception type, how an exception travels up the call stack, why exception handling can be cleaner than checking input first, the else and finally clauses, the exception object and raising your own exceptions. The debugging part introduces pyflakes, pylint, PyChecker and pep8, the pdb debugger and the logging module with its five levels. The subsection titled The with statement is left empty in this edition.

Key Points:

  • Syntax errors stop the program before it runs, runtime errors raise exceptions, and logical errors give wrong output with no message.
  • Catch a specific exception such as ValueError; a bare except also hides bugs you did not predict.
  • Code in the else clause runs only when the try block raised nothing, and finally always runs.
  • An unhandled exception climbs the call stack and the traceback shows its path; if nothing handles it, the program ends.
  • Raise TypeError for a wrong type, ValueError for the right type with a wrong value, and NotImplementedError for methods a subclass must provide.
  • python3 -m pdb program.py steps through a program; the dated tools pep8 and PyChecker are now pycodestyle and other linters.
  • Logging levels from most to least severe are CRITICAL, ERROR, WARNING, INFO and DEBUG.

Practice Tip: Write a loop that keeps asking for an integer and catches ValueError to ask again, as in Exercise 2. Type a letter, a blank line and a valid number to see each path.

Common Mistake: Wrapping a whole program in one try with a bare except. Protect only the line that can fail and name the exception you expect.

Important Questions:

  • What are the three kinds of programming error? Syntax errors (invalid code), runtime errors (valid code that fails while running) and logical errors (the program runs but gives a wrong result).
  • Why use the else clause of try? It holds code that should run only when no exception occurred, so those statements are not accidentally protected by the except clause.

Chapter 8: Functions

Difficulty: Medium · Key topics: def, parameters, return values, call stack, recursion, default parameters, *args and **kwargs, decorators, lambdas, generators

Chapter 8 covers functions as the way to remove duplicated code. It starts with def, naming advice and the fact that a function is an object, then parameters without declared types and return values (None by default). The call stack section explains stack frames and name lookup, and recursion uses Fibonacci with an iterative alternative. Later sections cover default parameters and the mutable-default trap, *args and **kwargs, decorators written as a log function, lambdas and generator functions that use yield. Each topic ends with a short exercise.

Key Points:

  • A function with no return statement returns None.
  • Parameters have no declared types, so one function works on any compatible values; test carefully because Python will not check.
  • Every recursive function needs an end case that does not call itself.
  • A default value is created once, when the function is defined, so use None as the default and build a new list inside the body.
  • *args collects extra positional arguments in a tuple and **kwargs collects keyword arguments in a dict.
  • @log above a function means exactly my_function = log(my_function).
  • A function that contains yield returns a generator that produces its values one at a time.

Practice Tip: Run the my_gen example and add a print just before the yield. You will see the function resume after the last yield with its local variables intact; the book’s wording that it runs again from the beginning is loose.

Common Mistake: Using an empty list as a default parameter. Every call that omits the argument shares the same list, so a second call returns the items from the first.

Important Questions:

  • Why does add_pet_to_list("dog") also return the cat when the default is pets=[]? The default list is created once at definition time and reused. Use pets=None and create the list inside the function.
  • What does a decorator do? It takes a function and returns a replacement, for example one that logs a message and then calls the original, and @name above a definition applies it.

Chapter 9: Classes

Difficulty: Medium · Key topics: class, __init__, self, instance and class attributes, classmethod, staticmethod, property, dir, magic methods

Chapter 9 introduces classes through a Person example. It covers the class keyword, __init__ as the initialiser (not strictly a constructor), self, instance attributes and the advice to create every attribute in __init__, plus getattr, setattr and hasattr. Class attributes such as a TITLES tuple are shared by all instances. The @classmethod, @staticmethod and @property decorators come next, with getters and setters. The chapter finishes with dir() and __dict__ for inspecting an object and overriding magic methods such as __str__ and the comparison methods, with notes on Python 2 differences.

Key Points:

  • A class is a type, an object is an instance of it, data stored on it are attributes and its functions are methods.
  • __init__ runs when an instance is created; self is the instance and is passed in automatically as the first argument.
  • Create all instance attributes in __init__, even as empty values, so an attribute never exists in some objects and not others.
  • A class attribute such as TITLES is shared by all instances and is a good place for constants.
  • @classmethod receives the class as cls, @staticmethod receives neither self nor cls, and @property lets a method be read like an attribute.
  • dir(obj) lists an object’s attributes and obj.__dict__ holds its instance attributes.
  • __str__ controls how str() shows an object, and methods such as __eq__ control comparison operators.

Practice Tip: Do Exercise 6: write a class whose __init__ accepts any keyword arguments and stores them with setattr, then add a __str__ that prints the class name and every attribute.

Common Mistake: Creating new attributes outside __init__. Other methods may then run before the attribute exists, which is why the book’s age example needed a hasattr check.

Important Questions:

  • What is self and why is it missing from the method call? It is the object the method was called on. Python passes it automatically as the first argument, so you write it in the definition but not in the call.
  • How do a class method and a static method differ? A class method gets the class as cls and can use class attributes; a static method gets neither the class nor the instance and is just a function grouped inside the class.

Chapter 10: Object-Oriented Programming

Difficulty: Hard · Key topics: encapsulation, composition, inheritance, super, multiple inheritance, mix-ins, abstract classes, duck typing, delegation

Chapter 10 applies classes to design. It starts with why object orientation helps larger programs and the principle of encapsulation, with a leading underscore as Python’s convention for private names. Composition is shown with Student, Department, Course and CourseRunning classes and described as one-to-many and many-to-many relationships. Inheritance follows with Person, Student, StaffMember and Lecturer, calling the parent’s __init__ with super. Later sections cover multiple inheritance and the diamond problem, mix-ins, abstract classes built with NotImplementedError, polymorphism without a shared parent, and replacing inheritance with composition and delegation.

Key Points:

  • Encapsulation means using an object’s data through its methods; Python relies on the underscore convention rather than enforcing privacy.
  • Composition is a has-a relationship and inheritance is an is-a relationship.
  • A subclass that overrides __init__ must call the parent’s version; the book writes super(Student, self).__init__(...), and in Python 3 plain super().__init__(...) does the same.
  • With multiple inheritance, two parents defining the same method cause the diamond problem; super calls the parent initialisers in a sensible order.
  • A mix-in is a small class that adds optional behaviour to another class and is not meant to stand alone.
  • Python cannot block instantiation, so the book builds abstract classes by raising NotImplementedError from their methods.
  • Polymorphism in Python does not need a shared parent class; any object with the right methods and attributes will work.

Practice Tip: Do Exercise 3: write a Box class whose methods raise NotImplementedError, then ListBox and DictBox subclasses, and a repack_boxes function that works on both.

Common Mistake: Reaching for deep or multiple inheritance by default. The book’s own Learner and Teacher rewrite shows that attributes plus delegation often give the same result with less confusion.

Important Questions:

  • What is the difference between composition and inheritance? Composition makes one object an attribute of another (a person has a birthdate); inheritance makes a class a specialised kind of another (a lecturer is a staff member).
  • Why can one function accept both Lecturer and Student objects without a common parent? Python checks behaviour, not type. If both objects have the attributes and methods the function uses, it works.

Chapter 11: Packaging and Testing

Difficulty: Medium · Key topics: modules, packages, setup, docstrings, Sphinx, unit tests, black-box and glass-box testing, unittest, trace. Packaging tools in this chapter are dated.

Chapter 11 covers organising and checking larger programs. Modules (each file is one) and packages (a directory with an __init__.py) are explained with an example package named ourprog, split into db, gui and rules modules, packaged with a setup() call using Distribute and then installed. The documentation section explains docstrings in a Sphinx-compatible format. The long testing section separates unit, integration and functional tests, black-box testing by equivalence classes and boundary values against glass-box path coverage, unittest TestCase classes with setUp, and a coverage check with the trace module.

Key Points:

  • Every .py file is a module; a directory containing __init__.py is a package.
  • Dated: the chapter packages with the Distribute library and python3 setup.py install; today you would use setuptools with pyproject.toml and install with pip.
  • A docstring is the string placed right after a def or class line; Sphinx can turn docstrings into documentation.
  • Unit tests check single functions or methods; integration tests check how components work together.
  • Black-box tests pick inputs from equivalence classes and boundary values; glass-box tests follow paths through the code.
  • A unittest.TestCase subclass holds test methods; setUp runs before each test and assertEqual compares results.
  • Write a new test whenever you fix a bug, so the same mistake is caught if it returns.

Practice Tip: For the phone-call cost program in Exercise 1, list the equivalence classes and boundary values first, put the calculation in an importable function, and only then write the unittest cases.

Common Mistake: Testing only typical values. Bugs gather at boundaries such as 49 and 50 or 79 and 80, where < versus <= decides the result.

Important Questions:

  • What is the difference between black-box and glass-box testing? Black-box tests are chosen from what the function should do (equivalence classes and boundaries); glass-box tests are chosen by reading the code and covering its paths.
  • What does setUp do in a TestCase? It runs before every test method so each test starts with fresh objects; tearDown runs after each test.

Chapter 12: Useful Modules in the Standard Library

Difficulty: Medium · Key topics: datetime, math, random, re, csv, sys, argparse, scripts versus libraries

Chapter 12 is a tour of standard-library modules. It starts with datetime (date, time, datetime, timedelta, timezone), then math with a pointer to cmath for complex numbers, and random with the idea of pseudo-random sequences that can be reproduced. The longest part is re: a regular-expression primer, the search, match, sub, findall, split and compile functions, greedy matching, replacement functions and flags. The chapter ends with the csv reader and writer, and sys and argparse for scripts and command-line parameters, including the difference between a script and a library.

Key Points:

  • Subtracting two dates or datetimes gives a datetime.timedelta.
  • Random numbers from random are pseudo-random, so the same sequence can be reproduced when debugging or testing.
  • Use raw strings for regular expressions so backslashes do not need to be doubled.
  • re.search finds a match anywhere, re.sub replaces, re.findall returns all matches and re.compile returns a reusable pattern object.
  • The flags re.IGNORECASE, re.MULTILINE and re.DOTALL can be combined with |.
  • csv.reader and csv.writer take optional delimiter and quote-character parameters.
  • sys.argv suits one or two simple arguments; argparse adds flags, optional values and automatic --help text.

Practice Tip: Build the guessing game from Exercise 3 with random.randint(1, 100), printing too high or too low and counting the guesses. Then reuse it in Chapter 13 as a GUI.

Common Mistake: Trusting the book’s line that re.match needs the whole string to match. In Python it only anchors at the start of the string; use re.fullmatch when the entire string must match.

Important Questions:

  • Why are numbers from the random module called pseudo-random? They come from a predictable algorithm, so they only look random, which also lets you repeat the exact same sequence in a test.
  • When should you use argparse instead of sys.argv? When a script needs several arguments, optional flags or help text, because argparse defines them and reports usage errors for you.

Chapter 13: Introduction to GUI Programming with tkinter

Difficulty: Medium · Key topics: event-driven programming, widgets, pack, grid, place, bind, StringVar, validatecommand, mainloop

Chapter 13 introduces graphical programs with tkinter, framed as event-driven object-oriented code. A first window with a Label and two Buttons shows the widget tree, the root Tk window, the pack geometry manager, command handlers and mainloop. The chapter lists the common widget classes, compares pack, grid and place layouts, and shows custom events with bind and a StringVar-controlled label. It finishes with a small adder application that validates an Entry field with validatecommand and updates a running total through an IntVar. The application class uses composition instead of inheriting from tkinter.

Key Points:

  • An event is anything the user does; an event handler is the function that runs in response.
  • Tk() creates the root window, widgets form a tree of parents and children, and root.mainloop() waits for events until the window closes.
  • The command= option attaches a handler to a Button.
  • Never mix pack and grid in one window; place is rarely a good choice.
  • widget.bind("<Button-1>", handler) hooks other events, and the handler receives an event object.
  • A label’s text changes through a StringVar or IntVar, not by editing a Python string.
  • Input validation uses validate="key" with a validatecommand that returns True or False and is wrapped with register.

Practice Tip: Type in the first window, then rebuild it with grid(row=..., column=...) and sticky instead of pack to see how the layout changes. Keep each window on one geometry manager.

Common Mistake: Mixing pack and grid in the same window. The two layout algorithms conflict and the program hangs.

Important Questions:

  • Why does the adder example wrap its button handlers in lambdas? The command option calls a function with no arguments, but the shared handler needs to know which button was pressed, so the lambda passes that value in.
  • What does mainloop() do? It runs forever, waiting for user events and calling their handlers, until the window is closed or the program is interrupted.

Chapter 14: Sorting, Searching and Algorithm Analysis

Difficulty: Hard · Key topics: selection sort, merge sort, linear search, binary search, Timsort, time and space complexity, Big O

The last chapter introduces algorithm analysis through four algorithms: selection sort, merge sort, linear search and binary search. Each is explained step by step on a small list of floats, with counts of comparisons, swaps and assignments and the algorithm written as numbered steps. The book names Timsort as Python’s own sorting algorithm and lists other sorts and searches that exist. It then explains time and space complexity and Big O notation, with best, expected and worst-case tables, and the exercises practise dropping constants and lower-order terms.

Key Points:

  • Time complexity counts steps as the input grows; space complexity counts the extra memory needed.
  • Selection sort takes O(N^2) time in the best, expected and worst case and is in-place. The book calls it stable, but a swap-based selection sort can reorder equal items, so check with a case like [2a, 2b, 1].
  • Merge sort takes O(N log N) time and O(N) extra space for its temporary list.
  • Linear search is O(1) at best and O(N) on average and worst case; binary search needs a sorted list and takes O(log N).
  • Big O drops constant factors and lower-order terms, so O(N^3 + N^2) becomes O(N^3).
  • Python’s sorted() and list.sort() use Timsort, a modified merge sort that uses insertion sort on short runs.
  • No sorting algorithm that only compares items can use fewer than O(N log N) comparisons.

Practice Tip: Write merge sort as in Exercise 3, with a separate merge function, and count comparisons for lists of 8, 16 and 32 items. The count should grow a little faster than the list size, in line with N log N.

Common Mistake: Running binary search on a list that is not sorted. It discards half the list each step on the assumption of order, so it returns wrong answers on unsorted data.

Important Questions:

  • Why would you ever use linear search when binary search is faster? Binary search needs a sorted list; linear search works on any list, and sorting first costs extra.
  • What is the Big O of 4N^2 + 2N + 2? O(N^2), because the constant factor 4 and the lower-order terms are dropped.

How to Study This Book

These are university course notes, and the object-oriented material comes late. Chapters 1 to 8 are a complete first programming course (variables, selection, collections, loops, exceptions, functions). Classes start in Chapter 9 and design with inheritance and composition in Chapter 10. If you already program in another language, read Chapter 2 for syntax, skim Chapters 3 to 8, and start properly at Chapter 9.

For an Object-Oriented Programming course, treat Chapters 9 and 10 as the core and the earlier chapters as prerequisites. Two dependencies matter most: the decorators in Chapter 8 are needed for @classmethod, @staticmethod and @property in Chapter 9, and the exception classes from Chapter 7 are needed for Exercise 2 of Chapter 10, which asks for a custom exception hierarchy. Read Chapter 7 before Chapter 10, not after.

Be clear about the Python version. The book targets Python 3 and shows 2013 to 2014 era tools (an interpreter banner of 3.2.3, documentation links to 3.3), with notes on Python 2.7 differences. The core language chapters still hold. The parts that have dated are: the Distribute and easy_install packaging in Chapter 11, the pep8 and PyChecker tools in Chapter 7, the statement that dictionaries are unordered in Chapter 5 (they keep insertion order since Python 3.7), a Python 2 print statement in the answer to Exercise 3 of Chapter 4, and the old-style super(Class, self) form. The language features it teaches are all still part of Python 3.

Check three statements against the real behaviour of Python. The generator description in Chapter 8 says the function runs again from the beginning, but a generator resumes after its last yield. The Chapter 12 text says re.match must match the whole string; it only anchors at the start, and re.fullmatch is the whole-string test. The Chapter 14 text calls its swap-based selection sort stable, which it generally is not. The Chapter 7 subsection titled The with statement is empty, but Chapter 2 already explains with.

Chapters 12, 13 and 14 are optional for many courses. Use Chapter 12 as a reference for datetime, re, csv and argparse. Read Chapter 13 only if your course includes GUI work; modern tkinter code often uses the themed ttk widgets, which the chapter does not cover. Chapter 14 belongs to a data structures and algorithms course, but it is a good first look at Big O. Chapter 1 has history that is rarely examined, so skim the generations of computers.

Every chapter from 2 to 14 ends with exercise sets and worked answers, about 60 sets in total, and many build on earlier ones (for example Chapter 7 Exercise 2 extends Chapter 6 Exercise 7). Type the code instead of reading answers first. The book does not cover type hints, dataclasses, the abc module, virtual environments, pytest, databases or web programming, so add those from a second source if your syllabus asks for them.


Used In These Programs

This book is used for the Object-Oriented Programming (Python) course in: BS Computer Science · BS Information Technology. Browse all Object-Oriented Programming books, all Python books or all Computer Science books.

Who Should Read This

This book suits BSCS and BSIT students who meet Python through a Programming Fundamentals or Object-Oriented Programming course, usually early in the degree, and students who know C++ or Java and need to see how classes, inheritance and exceptions work in Python. Chapters 1 to 8 assume no programming background. It is plain text with exercises but no quizzes or videos, so type every example. It is not a guide to modern Python features, data science libraries or web frameworks. For a gentler first Python book, pair it with Think Python, and if your course also teaches C++ OOP, compare Chapters 9 and 10 with Object Oriented Programming Using C++.


Applicable Universities

This book is useful for students at Pakistani universities offering BS Computer Science and BS Information Technology, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.

Official Copy of Object-Oriented Programming in Python

This book is free from its official site. There is no official PDF, so the legitimate way to read it is the online edition. Click the button below to open the book on Read the Docs and read it chapter by chapter.

→ Visit Official Page

FAQs

Is Object-Oriented Programming in Python free?

Yes. The University of Cape Town and its contributors release the book under the Creative Commons Attribution-ShareAlike 4.0 International licence (CC BY-SA 4.0). You may read it, share it and adapt it, even commercially, if you give credit and share your changes under the same licence. This page links to the official site and does not host the book.

Is there a PDF of this book?

There is no official PDF. The Read the Docs project page lists no PDF, ePub or HTML download, so the legitimate way to read it is online. The reStructuredText source is public on GitHub for anyone who wants to study or build it.

Is it still worth reading in 2026, and which Python version does it use?

It teaches Python 3, with notes on Python 2.7 differences, and its examples come from the 2013 to 2014 era. The language chapters still hold, but some tools are dated: Distribute and easy_install for packaging, and the pep8 and PyChecker linters. It does not cover f-strings, type hints, dataclasses or the abc module, and one answer in Chapter 4 still uses a Python 2 print statement.

How many chapters does it have, and are there exercises?

There are 14 chapters, from an introduction to computers up to sorting, searching and Big O. Chapters 2 to 14 end with exercises and worked answers, about 60 exercise sets in all. Classes begin in Chapter 9 and object-oriented design in Chapter 10.

Is it good for complete beginners?

Yes for the Python part. Chapter 1 starts from what a computer is and Chapters 2 to 8 assume no programming. It is text-only course notes with no quizzes, videos or auto-graded tasks, so you need to type and run the examples yourself.

Does it cover inheritance, multiple inheritance and abstract classes?

Yes. Chapter 10 covers composition, inheritance with super, multiple inheritance and the diamond problem, mix-ins, abstract classes built with NotImplementedError, and replacing inheritance with composition. It does not cover the abc module, dataclasses or design patterns.

Related Books

Object-Oriented Programming in Python is a free, plain set of university notes that takes you from your first print statement to classes, inheritance, testing and Big O. It is not a guide to modern Python libraries, but it gives you the object-oriented foundation most BSCS and BSIT courses expect. Browse more Computer Science books for the rest of your semester.

Object-Oriented Programming in Python by the University of Cape Town and individual contributors. Copyright 2013, 2014 University of Cape Town and individual contributors. Licensed under the Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0). Official source: https://python-textbok.readthedocs.io/en/latest/ . Source code: https://github.com/confluence/python-textbok . This page links to the official site and does not host or copy the book.

Leave a Comment