Introduction

Getting Started · Python 1

What Python Is

Python is an interpreted, dynamically typed language. You write source code in a .py file and the Python interpreter runs it line by line; there is no separate compile step. Variables take whatever type you put in them, and indentation, not braces, marks which lines belong together.

What you need
Two ways to run Python
  • Python 3 from python.org (Windows and Mac) or your package manager. Check with python3 --version; anything 3.8 or newer is fine for a first course.
  • An editor: VS Code with the Python extension, PyCharm Community, Thonny, or IDLE, which ships with Python.
  • Interactive shell — type python3, then statements one at a time at the >>> prompt. Great for trying things.
  • Script — save a file such as hello.py and run python3 hello.py. This is how programs are delivered.

Your First Program

hello.py

# My first Python program
print("Hello, World!")

Run it from a terminal

python3 hello.py
Hello, World!

Read it

  • Lines starting with # are comments for people; Python ignores them.
  • print(...) is a function call: the name, then the arguments in parentheses.
  • The text in quotes is a string. Single or double quotes both work; be consistent.
  • No semicolons, no braces, no main required: statements at the top of the file run in order.

More print

print("Hello", "World")          # separate arguments are joined with a space
print("The answer is", 6 * 7)    # numbers print too
print("No newline", end=" ")     # change what comes at the end
print("here")
print()                          # an empty line
Hello World
The answer is 42
No newline here

Indentation and Style

Where Java uses braces, Python uses a colon and a consistently indented block. Use four spaces per level and never mix tabs and spaces. Everything indented under a line ending in : belongs to it.

if hours > 40:
    print("Overtime")            # inside the if
    pay = pay * 1.5
print("Done")                    # outside: runs every time

Conventions (PEP 8)

  • Variables and functions in snake_case: total_score, print_balance()
  • Classes in UpperCamelCase: BankAccount
  • Constants in ALL_CAPS: MAX_SIZE = 100 (by convention; Python cannot stop you changing them)
  • Blank lines between functions, spaces around operators, lines under about 80 characters.

Comments and docstrings

# A one-line comment

"""
A docstring: a string on its own at the top of a file,
function or class, describing what it is for.
Tools and help() read it.
"""

Three Kinds of Errors

KindWhen it shows upExample
Syntax errorBefore anything runs; Python points at the lineA missing colon after if x > 0, unbalanced parentheses, wrong indentation
Run-time error (exception)While running; the program stops with a tracebackZeroDivisionError, NameError for a misspelled variable, TypeError for "3" + 4
Logic errorNever announced; the program runs and gives the wrong answerUsing / where you meant //, a loop that stops one early

What a traceback looks like

average.py

total = 0
count = 0
print(total / count)
Traceback (most recent call last):
  File "average.py", line 3, in <module>
    print(total / count)
          ~~~~~~^~~~~~~
ZeroDivisionError: division by zero
  • 1. Read the last line first: the exception name (ZeroDivisionError) and its message (division by zero) say what went wrong.
  • 2. The line above it (line 3) says where. Python 3.11 and later also underline the exact expression.
  • 3. If several File lines are listed, the bottom one is where the error happened and the ones above are the calls that led there.

Read the traceback from the bottom. The last line names the error and explains it; the lines above show the file and line number where it happened.

Programming with Numbers and Strings

Getting Started · Python 1

Variables and Types

A variable is a name for a value. You do not declare a type: Python looks at the value. The same name can later hold a different type, though good programs avoid that.

cans_per_pack = 6          # int
can_volume = 0.335         # float
done = False               # bool: True or False (capital letters)
name = "Harry"             # str
MAX_SIZE = 100             # a constant by convention

print(type(can_volume))    # <class 'float'>
cans_per_pack = cans_per_pack + 1   # update: read the old value, store the new
TypeHoldsNotes
intWhole numbersUnlimited size: 2 ** 100 just works
floatDecimal numbersAbout 15 significant digits; 0.1 + 0.2 == 0.3 is False
boolTrue or FalseThe result of every comparison
strTextImmutable: methods return new strings instead of changing the old one
None“no value”What a function returns when it has no return

Arithmetic

OperatorMeaningExample
+ - *Add, subtract, multiply7 * 3 → 21
/Division, always a float7 / 2 → 3.5; 6 / 3 → 2.0
//Floor division: the whole part7 // 2 → 3; -7 // 2 → -4
%Remainder (modulus)7 % 2 → 1; n % 2 == 0 tests for even
**Power2 ** 10 → 1024; x ** 0.5 is a square root
+= -= *= /=Combine and assigntotal += price. There is no ++ in Python.

Common math

import math

minutes = 135
hours = minutes // 60          # 2
left = minutes % 60            # 15
r = math.sqrt(2)               # 1.4142135623730951
area = math.pi * 3 ** 2
whole = int(19.99)             # 19: int() truncates
nearest = round(19.99)         # 20
two_dp = round(3.14159, 2)     # 3.14
big = max(3, 9, 4)             # 9
dist = abs(-4.5)               # 4.5

import random
dice = random.randint(1, 6)    # 1 to 6, inclusive

Integer division in Java (7 / 2 → 3) is 7 // 2 in Python. Python’s / never drops the fraction, so the classic “average is a whole number” bug does not happen here.

Strings

greeting = "Hello"
n = len(greeting)              # 5: a function, not a method
first = greeting[0]            # 'H'  (positions start at 0)
last = greeting[-1]            # 'o'  (negative counts from the end)
part = greeting[1:3]           # 'el' (from 1 up to, not including, 3)
start = greeting[:2]           # 'He'
rest = greeting[2:]            # 'llo'
where = greeting.find("l")     # 2, or -1 if not found
loud = greeting.upper()        # 'HELLO'
both = greeting + ", World"    # concatenation needs strings on both sides
rep = "-" * 10                 # '----------'
same = greeting == "Hello"     # True: == compares the letters
inside = "ell" in greeting     # True

Useful string methods

MethodDoes
s.lower(), s.upper()Change case
s.strip()Remove spaces and newlines at both ends
s.replace("a", "b")A new string with every a replaced
s.split(",")A list of pieces
",".join(items)Glue a list of strings together
s.startswith("Dr"), s.isdigit()Tests that return True or False
s.count("a")How many times

Converting

count = int("42")              # str to int
price = float("3.95")          # str to float
text = str(42)                 # number to str
int("3.5")                     # ValueError: not a whole number
"Total: " + 7                  # TypeError: use str(7) or an f-string

Strings are immutable. greeting[0] = "J" is an error. Build a new string instead: "J" + greeting[1:].

Input and Formatted Output

volume.py

bottles = int(input("Please enter the number of bottles: "))
price = float(input("Price per bottle: "))
total = bottles * price
print(f"Total: ${total:.2f} for {bottles} bottles")
Please enter the number of bottles: 3
Price per bottle: 1.5
Total: $4.50 for 3 bottles
Inside an f-stringMeaningExample
{x}The value of xf"{name} is {age}"
{x:.2f}Float with 2 decimalsf"{price:.2f}" → 3.50
{x:8.2f}Right-aligned in 8 columnsLines up a column of numbers
{x:5d}Integer in 5 columns
{s:<10}, {s:>10}, {s:^10}Left, right, center in 10 columns
{x:,}Thousands separatorsf"{1234567:,}" → 1,234,567

input() always returns a string, even when the user types a number. Convert with int() or float() before doing arithmetic.

Decisions

Control Flow · Python 1

The if Statement

if floor > 13:
    actual_floor = floor - 1
elif floor == 13:
    print("There is no 13th floor.")
else:
    actual_floor = floor
Relational operators
Boolean operators
PythonMathNote
> >=> ≥
< <=< ≤
===Two equals signs. One = assigns, and is a syntax error inside an if.
!=≠
0 < x < 100 < x < 10Chained comparisons work in Python
OperatorTrue when
a and bboth are true
a or bat least one is true
not aa is false

and and or short-circuit: in x != 0 and 1 / x > 2 the division is skipped when x is 0.

Comparing Strings, Decimals and Nothing

if word == "quit":                  # strings compare by content
if word.lower() == "quit":          # ignore case
if word < other:                    # alphabetical (uppercase sorts before lowercase)
if "a" in word:                     # substring test
if word:                            # True for any non-empty string

EPSILON = 1e-12
if abs(x - y) < EPSILON:            # floats: compare with a tolerance

if result is None:                  # test for "no value" with is, not ==
Counts as FalseCounts as True
False, None, 0, 0.0, "", [], {}Everything else, including "0" and " "

Because empty things are false, if items: is the usual way to ask “is there anything in the list?”

Nested Decisions, match and the Conditional Expression

Letter grade: each test assumes the earlier ones failed

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

match (Python 3.10 and later)

match digit:
    case 1:
        name = "one"
    case 2:
        name = "two"
    case _:                 # the default: leave it out and digit 7 sets nothing
        name = "many"

In the grade chain, a score of 95 passes the first test, so the later tests are never even looked at. Start from the other end (score >= 70 first) and every passing score would be a C. Without case _:, a value that matches nothing silently does nothing, and using name afterwards gives NameError: name 'name' is not defined.

Conditional expression

# One line, when both results are simple values
label = "even" if n % 2 == 0 else "odd"

Mistakes to Watch For

  • Forgetting the colon at the end of if, elif and else lines. Python says SyntaxError: expected ':' and points at the end of the line.
  • Inconsistent indentation inside a block. Four spaces, every time. A body that is not indented at all gives IndentationError: expected an indented block after 'if' statement on line 1.
  • One equals sign in a test: if x = 1: gives SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?. Comparison is ==.
  • if done == True: works but is noise; write if done:. Likewise if not done:.
  • Comparing a number to the string the user typed: input("Age: ") >= 18 gives TypeError: '>=' not supported between instances of 'str' and 'int'. Convert first with int(...).
  • An elif chain stops at the first true test, so order the ranges from largest down or smallest up.

Loops

Control Flow · Python 1

while and for

LoopUse it whenShape
whileYou do not know how many times; stop when a condition changeswhile balance < TARGET:
for ... in range(...)You count a known number of timesfor i in range(10): gives 0 to 9
for item in sequenceYou want each element of a string, list, file or dictionaryfor ch in word:
# while: years until the balance doubles
year = 0
while balance < 2 * initial:  # tested before every turn, including the first
    year += 1
    balance = balance + balance * RATE / 100   # moves toward the exit

# for with range: the count is known
for i in range(1, 11):            # 1 to 10; the end is not included
    print(i, "squared is", i * i)

# for over a sequence: no index needed
for ch in "Hello":
    print(ch)
1 squared is 1
2 squared is 4
...
10 squared is 100
H
e
l
l
o

Choosing a loop

  • 1. Do you know before the loop starts how many times it runs (a count, or len of something)? Use for i in range(...).
  • 2. Do you want each item of a string, list, file or dictionary, and never the position? Use for item in collection. If you need both, enumerate.
  • 3. Otherwise, when the stop depends on something computed as you go (a balance, user input, a guess), use while, and make sure the body changes a variable named in the condition, or it never ends.
  • 4. Must the body run at least once before the test makes sense (read, then check)? Use while True: with break.
CallProduces
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 10, 2)0, 2, 4, 6, 8
range(10, 0, -1)10 down to 1
range(len(items))every valid index of a list

Python has no do-while. Write while True: with a break when the exit condition is met, or ask once before the loop and again at the end of its body.

Common Loop Algorithms

Sum, average, count

total = 0
count = 0
line = input("Value (blank to finish): ")
while line != "":
    total += float(line)
    count += 1
    line = input("Value (blank to finish): ")
if count > 0:
    print("Average:", total / count)

Maximum and minimum

largest = values[0]           # start with the first value
for v in values:
    if v > largest:
        largest = v
# or simply: largest = max(values)

Sentinel value

salary = float(input("Salary, -1 to finish: "))
while salary != -1:
    total += salary
    salary = float(input("Salary, -1 to finish: "))

Prompting until valid, with while True

while True:
    value = int(input("Enter a positive number: "))
    if value > 0:
        break                # the only way out
print("You entered", value)

Counting matches

spaces = 0
for ch in text:
    if ch == " ":
        spaces += 1

Finding the first match

position = -1
for i in range(len(values)):
    if values[i] == target:
        position = i
        break

Nested Loops and Loop Tools

Nested loops: a table

for row in range(1, 4):
    for col in range(1, 5):
        print(f"{row * col:4d}", end="")
    print()                     # end the row
   1   2   3   4
   2   4   6   8
   3   6   9  12

enumerate and zip

for i, name in enumerate(names):          # index and value together
    print(i, name)

for name, score in zip(names, scores):    # two lists in step
    print(name, score)

for i, name in enumerate(names, start=1): # count from 1
    print(f"{i}. {name}")
  • break leaves the innermost loop; continue skips to the next turn.
  • A loop may have an else: that runs only when the loop finished without a break. It is rare; a flag variable is often clearer.
  • range(len(items)) is only needed when you must have the index. If you just need the items, loop over them directly.
  • Never change a list while looping over it; build a new list instead.

Off-by-One and Other Traps

  • range(1, n) stops at n - 1. For 1 through n write range(1, n + 1).
  • A while whose condition never changes is infinite. Ctrl+C stops it; then make sure the body moves toward the exit.
  • Float counters drift: x = 0; while x != 1: x += 0.1 never stops. Count with integers and compute the float inside.
  • The loop variable keeps its last value after a for finishes; do not rely on it.
  • for i in 10: gives TypeError: 'int' object is not iterable; you meant range(10). And range(n / 2) gives TypeError: 'float' object cannot be interpreted as an integer because / makes a float; use n // 2.
  • A loop body that only reads the loop variable but never changes anything else is usually missing the total += ... or count += 1 line. Decide before writing the loop what each turn must update.
  • Tracing by hand with a tiny input (n = 2) catches most loop bugs in a minute.

Functions

Control Flow · Python 1

Defining and Calling

A function packages a computation under a name so you can call it from many places and test it alone. def defines it; the function runs only when it is called. Define functions above the code that calls them.

def cube_volume(side_length):
    """Computes the volume of a cube with the given side length."""
    volume = side_length ** 3
    return volume

result = cube_volume(2)        # the call; 2 is the argument
print(result)                  # 8
print(cube_volume(1.5))        # 3.375
PartIn the exampleRules
Headerdef cube_volume(side_length):def, the name, parameters in parentheses, a colon
Docstring"""Computes ..."""First line of the body; say what it does and what it returns
Bodythe indented linesRuns each time the function is called
returnreturn volumeEnds the call and hands back a value. No return, or a bare return, gives None

Writing a function, step by step

  • 1. Say in one sentence what it computes, and name it for that: cube_volume, is_valid_score, print_report.
  • 2. The parameters are the values that differ from call to call. Anything you can compute from them belongs inside the body, not in the parameter list.
  • 3. Decide what comes back. A function that computes something ends in return; a function that only prints returns nothing. Do not mix the two in one function.
  • 4. Write the docstring, then the body. Put the return at the end, outside any loop, unless you mean to stop early.
  • 5. Test it alone in the shell with two or three inputs whose answers you know: cube_volume(1) is 1, cube_volume(2) is 8.

Parameters, Return Values and None

Several parameters and several results

def read_rect():
    width = float(input("Width: "))
    height = float(input("Height: "))
    return width, height           # a tuple

w, h = read_rect()                 # unpack it

def area_and_perimeter(w, h):
    return w * h, 2 * (w + h)

Default and keyword arguments

def greet(name, greeting="Hello", punctuation="!"):
    return f"{greeting}, {name}{punctuation}"

greet("Ann")                            # Hello, Ann!
greet("Ann", "Hi")                      # Hi, Ann!
greet("Ann", punctuation="?")           # Hello, Ann?

Functions without a return value

def box_string(contents):
    n = len(contents)
    print("-" * (n + 2))
    print(f"!{contents}!")
    print("-" * (n + 2))

box_string("Hello")           # prints; returns None
x = box_string("Hi")          # legal but pointless: x is None

Arguments are references

def add_interest(balance, rate):
    balance = balance + balance * rate / 100   # rebinds the local name only

def append_bonus(scores):
    scores.append(10)                          # changes the caller's list

savings = 1000
add_interest(savings, 5)
print(savings)            # still 1000

my_scores = [90, 85]
append_bonus(my_scores)
print(my_scores)          # [90, 85, 10]

A function cannot make the caller’s variable point at a new value, so for numbers and strings you return the result. It can change the inside of a mutable object such as a list that was passed in.

Scope and Stepwise Refinement

Local and global

counter = 0                  # global

def increment():
    global counter           # needed to ASSIGN a global; reading needs nothing
    counter += 1

def total(values):
    result = 0               # local: exists only during this call
    for v in values:         # v is local too
        result += v
    return result

Stepwise refinement

  • Write the top level as a list of calls to functions that do not exist yet, each named for one job: read_scores(), compute_average(), print_report().
  • Then write each function. If one gets long, split it again.
  • Keep functions short enough to read without scrolling, and give every one a docstring.
  • Put the program’s top level in a main() function and call it at the bottom, so the file can also be imported without running.

The usual skeleton

def main():
    scores = read_scores()
    average = compute_average(scores)
    print_report(scores, average)

# ... function definitions ...

if __name__ == "__main__":
    main()

Mistakes to watch for

  • Calling with too few arguments: cube_volume() stops with TypeError: cube_volume() missing 1 required positional argument: 'side_length'.
  • Using a local variable after the call: print(volume) outside the function gives NameError: name 'volume' is not defined. Locals vanish when the function returns; return the value instead.
  • Assigning to a global inside a function without global: counter += 1 gives UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value. Better still, pass the value in and return the new one.
  • Forgetting the parentheses: print(cube_volume) prints <function cube_volume at 0x...> instead of calling it.
  • A return indented inside the for loop ends the function on the first turn. Dedent it to sit after the loop.
  • Calling a function above the line that defines it. In a script, def must have run before the call, which is why main() is called at the bottom.

Lists

Data · Python 1

Creating and Indexing

A list holds a sequence of values in order. Lists grow and shrink, may mix types, and are mutable: you can change what is inside. Positions start at 0; negative positions count from the end.

values = [32, 54, 67.5, 29, 35]
empty = []
zeros = [0] * 10                 # ten zeros
first = values[0]                # 32
last = values[-1]                # 35
values[1] = 60                   # replace
n = len(values)                  # 5
values[5] = 1                    # IndexError: 5 is past the end
middle = values[1:3]             # [60, 67.5]: a new list, from 1 up to 3

Visiting every element

for v in values:                 # the values
    print(v)

for i in range(len(values)):     # when you need the position
    print(i, values[i])

for i, v in enumerate(values):   # both
    print(i, v)

Common list algorithms

total = sum(values)              # built in
largest = max(values)
smallest = min(values)
average = sum(values) / len(values)

# linear search by hand (or just: target in values)
position = -1
for i in range(len(values)):
    if values[i] == target:
        position = i
        break

# swap two elements
values[i], values[j] = values[j], values[i]

List Methods and Aliasing

OperationDoesReturns
lst.append(x)Adds x to the endNone (changes the list in place)
lst.insert(i, x)Puts x at position i, later ones shift rightNone
lst.pop() / lst.pop(i)Removes and returns the last / the i-th elementthe element
lst.remove(x)Removes the first x; ValueError if absentNone
lst.index(x)Position of the first x; ValueError if absentan int
x in lstMembership testTrue or False
lst.sort()Sorts in placeNone
sorted(lst)A new sorted list, the original untoucheda list
lst.reverse(), lst.count(x), lst.extend(other)Reverse in place; count; append every element of other

Aliasing

a = [1, 2, 3]
b = a                 # b is another NAME for the same list
b.append(4)
print(a)              # [1, 2, 3, 4]

c = list(a)           # a real copy (or a[:] or a.copy())
c.append(5)
print(a)              # [1, 2, 3, 4]: unchanged

Slices

nums = [10, 20, 30, 40, 50]
nums[1:3]        # [20, 30]
nums[:2]         # [10, 20]
nums[3:]         # [40, 50]
nums[::2]        # [10, 30, 50]
nums[::-1]       # reversed copy
nums[1:3] = [7]  # replace a slice: [10, 7, 40, 50]

Assignment does not copy a list. After b = a both names see every change. Copy on purpose when you need two independent lists.

Mistakes to watch for

  • values[len(values)] is one past the end: IndexError: list index out of range. The last valid position is len(values) - 1, or just values[-1].
  • values = values.append(x) throws the list away: append changes the list and returns None, so values is now None. The same goes for values = values.sort(). Call them on their own line.
  • for i in range(values): gives TypeError: 'list' object cannot be interpreted as an integer. range wants a count: range(len(values)).
  • A position computed with /: values[len(values) / 2] gives TypeError: list indices must be integers or slices, not float. Use //.
  • Removing elements while looping over the same list skips the neighbours of each removed item. Loop over a copy, or build a new list with a comprehension.

List Comprehensions, Tuples and Tables

List comprehensions

squares = [x * x for x in range(1, 6)]            # [1, 4, 9, 16, 25]
evens = [x for x in values if x % 2 == 0]        # filter
names_upper = [n.upper() for n in names]
# equivalent loop:
squares = []
for x in range(1, 6):
    squares.append(x * x)

Tuples: lists that cannot change

point = (3, 4)
x, y = point                # unpacking
rgb = 255, 128, 0           # parentheses optional
point[0] = 1                # TypeError: tuples are immutable
# Use a tuple for a fixed group of related values,
# such as a coordinate or a function's several results.

Two-dimensional lists

# A table: a list of rows, each row a list
table = [[0] * 4 for _ in range(3)]      # 3 rows of 4 zeros (NOT [[0]*4]*3: that aliases the rows)
table[1][2] = 7
for row in table:
    for value in row:
        print(f"{value:4d}", end="")
    print()

rows = len(table)
cols = len(table[0])
column_total = sum(table[r][1] for r in range(rows))

Files and Exceptions

Data · Python 1

Reading and Writing Text Files

line_numberer.py

# Copy input.txt to output.txt with line numbers
with open("input.txt", "r") as infile, open("output.txt", "w") as outfile:
    line_number = 1
    for line in infile:                      # one line at a time, newline included
        outfile.write(f"/* {line_number} */ {line}")
        line_number += 1
# both files are closed automatically when the with block ends
CallDoes
open(name, "r")Opens for reading; FileNotFoundError if it does not exist
open(name, "w")Opens for writing; creates the file or erases an existing one
open(name, "a")Opens for appending at the end
for line in f:The usual way to read: every line, including its \n
f.read()The whole file as one string
f.readline()The next line, or "" at the end
f.readlines()A list of all lines
f.write(s)Writes a string; add \n yourself
print(x, file=f)Prints into the file, newline included

Reading a file safely, step by step

  • 1. Get the name from the user or sys.argv[1]; remember it is relative to the working directory.
  • 2. Open it in a with block so it is closed even if an error happens half way.
  • 3. Read for line in f: and rstrip() each line; the \n is still on it.
  • 4. Skip blank lines (if not line: continue) before converting; files often end with one.
  • 5. Convert with int or float inside try, catching ValueError, so one bad line does not kill the run.
  • 6. Put the open itself inside try/except FileNotFoundError where you can tell the user and ask again.
import sys

filename = sys.argv[1] if len(sys.argv) > 1 else input("File: ")
total = 0.0
try:
    with open(filename) as f:
        for line in f:
            line = line.strip()
            if not line:                       # blank line: skip
                continue
            try:
                total += float(line)
            except ValueError:
                print("Skipping bad line:", repr(line))
except FileNotFoundError:
    print("No such file:", filename)
else:
    print("Total:", total)

Taking a line apart

line = "Smith, Jane, 92\n"
line = line.rstrip()               # drop the newline
parts = line.split(", ")           # ['Smith', 'Jane', '92']
score = int(parts[2])

for line in infile:
    for word in line.split():      # whitespace-separated words
        count += 1

Reading numbers

# One number per line
with open("numbers.txt") as f:
    values = [float(line) for line in f if line.strip()]

# Several per line
for line in f:
    for token in line.split():
        total += float(token)

File names are relative to the working directory, usually the folder you ran Python from. The sys.argv list holds command-line arguments: python3 prog.py input.txt gives sys.argv[1] == "input.txt".

Mistakes to watch for

  • FileNotFoundError: [Errno 2] No such file or directory: 'input.txt' almost always means the working directory is not the folder the file is in. Print os.getcwd() to see where Python is looking.
  • ValueError: invalid literal for int() with base 10: '' is the blank line at the end of the file. Skip empty lines before converting.
  • f.write(42) gives TypeError: write() argument must be str, not int. Write str(42) or an f-string, and add the \n yourself or every value lands on one line.
  • Opening the input file with "w" erases it before you read a byte. Reading is "r", the default.

Exceptions

When something goes wrong at run time Python raises an exception. If nothing handles it, the program prints a traceback and stops. You can raise your own and handle the ones you can recover from with try/except.

Raising

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Amount exceeds balance")
    return balance - amount

Handling

try:
    with open(filename) as f:
        value = int(f.readline())
    print("Read", value)
except FileNotFoundError:
    print("File not found:", filename)
except ValueError as e:
    print("Not a number:", e)
ExceptionRaised when
ValueErrorRight type, wrong value: int("abc"), math.sqrt(-1)
TypeErrorWrong type: "3" + 4, len(5)
IndexErrorA list or string position past the end
KeyErrorA dictionary key that is not there
ZeroDivisionErrorx / 0 or x % 0
FileNotFoundErroropen for reading a file that does not exist
NameError, AttributeErrorA misspelled variable; a method the object does not have

The Full try Statement and Your Own Exceptions

else and finally

try:
    f = open(filename)
except FileNotFoundError:
    print("Cannot open", filename)
else:
    data = f.read()           # runs only when no exception happened
    f.close()
finally:
    print("Done")             # runs no matter what

A custom exception class

class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(f"Balance is {balance}")
    return balance - amount

try:
    balance = withdraw(balance, 500)
except InsufficientFundsError as e:
    print("Sorry:", e)
  • Raise early: check arguments at the top of a function and raise with a clear message.
  • Catch late: handle where you can actually do something, usually in main or the input loop, not where the problem was found.
  • Catch the specific exception. A bare except: hides bugs, including typos, and even swallows Ctrl+C.
  • Never leave an except block as just pass. At least print the message.
  • Prefer with open(...) to finally: f.close(); it does the closing for you.

Sets and Dictionaries

Data · Python 1

Sets

A set holds values with no duplicates and no order. Adding a value that is already there does nothing. Use a set when the question is only “is it in there?” or to collect distinct things.

names = {"Romeo", "Juliet"}        # curly braces with values
empty = set()                      # NOT {} , which is an empty dictionary
names.add("Mercutio")
names.add("Romeo")                 # ignored: already present
print(len(names))                  # 3
print("Juliet" in names)           # True: very fast
names.discard("Romeo")             # no error if absent (remove() raises KeyError)
for name in sorted(names):         # sets have no order; sort for display
    print(name)

distinct = set(words)              # the distinct words in a list
OperationOperatorMethod
Union: in eithera | ba.union(b)
Intersection: in botha & ba.intersection(b)
Difference: in a but not ba - ba.difference(b)
Subset testa <= ba.issubset(b)

Set elements must be hashable: numbers, strings and tuples are fine; lists and other sets are not. Use a frozenset or a tuple when you need a set of sets.

Mistakes to watch for

  • seen = {} makes an empty dictionary (type({}) is <class 'dict'>), and seen.add(x) then fails with AttributeError: 'dict' object has no attribute 'add'. Write set().
  • Putting a list in a set: {[1, 2]} gives TypeError: unhashable type: 'list'. Convert it to a tuple first.
  • Printing a set and expecting the order you added things in. Sort it, or use a list if order matters.

Dictionaries

A dictionary stores key → value pairs. Each key appears once and looks up its value directly, like a word in a real dictionary. Keys are usually strings or numbers; values can be anything, including lists and other dictionaries.

contacts = {"Fred": 7235591, "Mary": 3841212}
contacts["Sarah"] = 2213278            # add or replace
number = contacts["Fred"]              # look up; KeyError if absent
number = contacts.get("Bob", 0)        # 0 instead of an error
if "Mary" in contacts:                 # key test
    del contacts["Mary"]               # or contacts.pop("Mary")
print(len(contacts))

for name in contacts:                  # keys, in insertion order
    print(name, contacts[name])
for name, number in contacts.items():  # key and value together
    print(f"{name}: {number}")
for number in contacts.values():
    print(number)

Counting with a dictionary

# How many times does each word occur?
counts = {}
for word in text.lower().split():
    counts[word] = counts.get(word, 0) + 1

# the most common word
best = max(counts, key=counts.get)

# or let the library do it:
from collections import Counter
counts = Counter(text.lower().split())
counts.most_common(3)

Grouping with a dictionary of lists

by_letter = {}
for name in names:
    key = name[0]
    if key not in by_letter:
        by_letter[key] = []
    by_letter[key].append(name)

# the same with setdefault
for name in names:
    by_letter.setdefault(name[0], []).append(name)

Dictionary comprehensions

squares = {x: x * x for x in range(1, 6)}      # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
inverted = {v: k for k, v in contacts.items()}  # swap keys and values

d[key] on a missing key raises KeyError. Use d.get(key, default) or test key in d first when the key might not be there.

Mistakes to watch for

  • counts[word] += 1 on a word not seen before: KeyError: 'apple'. Use counts.get(word, 0) + 1, setdefault, or a Counter.
  • Deleting while looping: for k in d: del d[k] stops with RuntimeError: dictionary changed size during iteration. Loop over list(d) instead.
  • Using a list as a key gives TypeError: unhashable type: 'list'; keys must be immutable (strings, numbers, tuples).

Choosing a Collection

You needUse
Values in order, by position, possibly repeateda list
A fixed group of related values that should not changea tuple
Membership only, no duplicatesa set
Look up a value by a keya dict
First in, first outcollections.deque (append and popleft)
Last in, first outa list with append and pop

Deciding, in order

  • 1. Will you look values up by a name, id or other key? dict.
  • 2. Is the only question “have I seen this before?” set.
  • 3. Does position matter, or can the same value appear twice? list.
  • 4. Is it a small fixed group that should never change, such as a coordinate? tuple.

Dictionaries keep insertion order (Python 3.7 and later). Sets do not promise any order, so sort before you print them. Picking a list where a set or dict belongs still works, but x in big_list checks every element while x in big_set is one step.

Objects and Classes

Objects and Algorithms · Python 1

Classes Describe, Objects Are

A class is a blueprint: it says what data each object carries (instance variables) and what each object can do (methods). An object is one instance, made by calling the class like a function. Strings, lists and files are objects of built-in classes; now you write your own.

bankaccount.py

class BankAccount:
    """A bank account has a balance that can be changed by deposits and withdrawals."""

    def __init__(self, initial_balance=0.0):
        """Constructs a bank account with the given balance (zero by default)."""
        self._balance = initial_balance

    def deposit(self, amount):
        """Deposits money into the account."""
        self._balance = self._balance + amount

    def withdraw(self, amount):
        if amount > self._balance:
            raise ValueError("Amount exceeds balance")
        self._balance = self._balance - amount

    def get_balance(self):
        """Gets the current balance."""
        return self._balance

    def __repr__(self):
        return f"BankAccount(balance={self._balance:.2f})"

Using the class

harrys_checking = BankAccount()          # calls __init__ with the default
moms_savings = BankAccount(5000)
harrys_checking.deposit(2000)
moms_savings.withdraw(500)
print(harrys_checking.get_balance())     # 2000.0
print(moms_savings)                      # BankAccount(balance=4500.00)

The Pieces of a Class

PieceLooks likeNotes
__init__def __init__(self, initial_balance=0.0):The constructor: runs when the object is created; sets up every instance variable
selffirst parameter of every methodThe object the method was called on. Python passes it for you: acct.deposit(50) runs deposit(acct, 50)
Instance variableself._balanceOne per object. The leading underscore means “private, please use the methods”; Python relies on convention, not enforcement
Mutator methoddeposit, withdrawChanges the object
Accessor methodget_balanceReports without changing
__repr__ / __str__def __repr__(self):What print(acct) shows; define one in every class

Object references

a = BankAccount(1000)
b = a                    # b refers to the SAME object
b.deposit(500)
print(a.get_balance())   # 1500.0

c = None                 # refers to nothing
c.deposit(1)             # AttributeError: 'NoneType' has no attribute 'deposit'

Class variables and properties

class BankAccount:
    _last_number = 1000              # shared by every account

    def __init__(self):
        BankAccount._last_number += 1
        self._number = BankAccount._last_number
        self._balance = 0.0

    @property
    def balance(self):               # read like a variable: acct.balance
        return self._balance

Forgetting self is the classic mistake: writing balance instead of self._balance inside a method creates a throwaway local variable, and leaving self out of a method header makes every call fail with a TypeError about arguments.

Mistakes to watch for

  • def deposit(amount): without self: acct.deposit(50) gives TypeError: BankAccount.deposit() takes 1 positional argument but 2 were given. The “2” is the object plus your argument.
  • acct.balance when the variable is self._balance, or was never set in __init__: AttributeError: 'BankAccount' object has no attribute 'balance'.
  • Creating an object without the constructor’s arguments: SavingsAccount() gives TypeError: SavingsAccount.__init__() missing 1 required positional argument: 'rate'.
  • No __repr__: print(acct) shows <BankAccount object at 0x7f...>. Define one before you debug anything else.

Special Methods and Design

Making objects behave like built-ins

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __eq__(self, other):              # ==
        return isinstance(other, Point) and self.x == other.x and self.y == other.y

    def __add__(self, other):             # +
        return Point(self.x + other.x, self.y + other.y)

    def __lt__(self, other):              # <, which also lets sorted() work
        return (self.x, self.y) < (other.x, other.y)

Designing a class, step by step

  • 1. Write one sentence saying what an object of the class is and what it is responsible for. If that takes two sentences, you have two classes.
  • 2. Start with the public interface: what should callers be able to do? Write the method headers and docstrings first.
  • 3. Then pick the instance variables that make those methods possible, and set every one in __init__.
  • 4. Add __repr__ immediately, so printing an object during testing shows its data.
  • 5. Every method should leave the object in a valid state. Test the class alone, in the shell or with a few assert lines, before using it elsewhere.
  • 6. A class should be about one thing. If you cannot say what an object of the class is in a sentence, split it.

Methods whose names start and end with double underscores (__init__, __repr__, __eq__, __len__, __getitem__) are called by Python itself in response to syntax. Define them and your objects work with print, ==, +, len() and indexing.

Inheritance

Objects and Algorithms · Python 1

Extending a Class

Inheritance builds a new class from an existing one. The subclass gets every method of the superclass and adds or changes what it needs. Read class SavingsAccount(BankAccount) as “a SavingsAccount is a special kind of BankAccount”.

savingsaccount.py

class SavingsAccount(BankAccount):
    def __init__(self, rate):
        super().__init__()               # let BankAccount set up the balance
        self._interest_rate = rate       # then add what is new

    def add_interest(self):
        """Adds the earned interest to the balance."""
        interest = self.get_balance() * self._interest_rate / 100
        self.deposit(interest)           # inherited methods, called on self

Overriding

class CheckingAccount(BankAccount):
    def __init__(self):
        super().__init__()
        self._transaction_count = 0

    def deposit(self, amount):                 # same name: replaces the inherited one
        self._transaction_count += 1
        super().deposit(amount)                # then do what the superclass does

    def __repr__(self):
        return f"CheckingAccount(balance={self.get_balance():.2f}, transactions={self._transaction_count})"

The rules

  • Call super().__init__(...) first in the subclass constructor, or the superclass’s instance variables never get set. The symptom appears later, in an inherited method: AttributeError: 'SavingsAccount' object has no attribute '_balance'.
  • A subclass method with the same name overrides the inherited one. Use super().method(...) inside it to extend rather than replace.
  • Everything is inherited, including “private” underscore variables; the underscore is a request, not a lock. Prefer the superclass’s methods anyway, so it can change its insides later.
  • Every class ultimately inherits from object, which is where the default __repr__, __eq__ and friends come from.

Polymorphism

accounts = [BankAccount(100), SavingsAccount(2.5), CheckingAccount()]

for acct in accounts:
    acct.deposit(10)        # the version that runs depends on the actual object
    print(acct)             # each class's own __repr__

for acct in accounts:
    if isinstance(acct, SavingsAccount):
        acct.add_interest()               # only savings accounts have this

Duck typing

  • Python does not check types when you call a method. Anything with a deposit method can go in that loop, related by inheritance or not: “if it walks like a duck…”
  • Inheritance is still worth it when classes genuinely share behavior you would otherwise copy, and it documents the “is a” relationship.
  • Use isinstance(obj, Class), not type(obj) == Class: the first is true for subclasses too.

Abstract base classes

from abc import ABC, abstractmethod

class Shape(ABC):
    def __init__(self, name):
        self.name = name

    @abstractmethod
    def area(self):            # subclasses MUST define this
        pass

    def describe(self):
        return f"{self.name} with area {self.area():.2f}"

class Circle(Shape):
    def __init__(self, r):
        super().__init__("circle")
        self.r = r

    def area(self):
        return 3.14159 * self.r ** 2

Shape("x")        # TypeError: can't instantiate an abstract class
Circle(2).describe()   # 'circle with area 12.57'

The full message is TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'. You also get it for Circle if you misspell area in the subclass, because the abstract method is then still missing.

Equality and Hashing

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return self.x == other.x and self.y == other.y

    def __hash__(self):                   # needed to put Points in a set or use them as dict keys
        return hash((self.x, self.y))

p = Point(1, 2)
q = Point(1, 2)
print(p == q)          # content
print(p is q)          # identity
print(len({p, q}))     # the set sees one point
print(p == (1, 2))     # NotImplemented on both sides, so False
True
False
1
False
  • Without __eq__, == on two objects means “the very same object”, like is.
  • If you define __eq__ you should define __hash__ the same way, or the objects cannot go in sets or be dictionary keys: Python silently removes the default hash and {p} fails with TypeError: unhashable type: 'Point'.
  • Return NotImplemented (not False) when the other object is a different type, so Python can try the other side.

Recursion

Objects and Algorithms · Python 1

A Function That Calls Itself

A recursive function solves a problem by solving a smaller version of the same problem, then doing one more step. Every recursion needs two things: a base case answered directly, and a recursive case that moves toward the base case.

Factorial

def factorial(n):
    if n <= 1:                     # base case
        return 1
    return n * factorial(n - 1)    # recursive case: smaller n

# factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * 1 = 24

Sum of digits

def digit_sum(n):
    if n < 10:
        return n
    return digit_sum(n // 10) + n % 10

# digit_sum(1729) = digit_sum(172) + 9 = (digit_sum(17) + 2) + 9 = ((1 + 7) + 2) + 9 = 19

Palindrome

def is_palindrome(s):
    if len(s) <= 1:
        return True
    if s[0] != s[-1]:
        return False
    return is_palindrome(s[1:-1])

Thinking recursively

  • Trust the recursive call. Assume is_palindrome works for shorter strings; your job is only the first and last letter.
  • Make sure each call is strictly smaller and that the smallest case is handled before any recursive call.
  • Trace tiny inputs by hand: the empty string, one character, two characters.

Writing a recursive function, step by step

  • 1. State the contract in one line: “digit_sum(n) returns the sum of the digits of n”. Everything below relies on it.
  • 2. Find the smallest input(s) and return the answer directly. For digit_sum that is a single digit; for strings and lists it is usually empty or length one.
  • 3. For any bigger input, peel off one piece (n % 10, s[0], values[-1]) and assume the function already works on what is left.
  • 4. Combine the piece with that result, and return it.
  • 5. Check that every recursive call is strictly smaller and that it cannot skip past the base case (negative numbers, odd lengths).
  • 6. Test the base case first, then one step above it, then something larger.

Mistakes to watch for

  • No base case, or one the input never reaches (factorial(-1) with if n == 0): RecursionError: maximum recursion depth exceeded, after about 1000 calls.
  • Forgetting the return in front of the recursive call: the call runs but its result is dropped, the function returns None, and the caller sees TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'.
  • Calling with the same argument (digit_sum(n) instead of digit_sum(n // 10)). The input must shrink on every call.

When Recursion Is Slow

# Fibonacci the obvious way: correct, but fib(35) makes about 30 million calls
def fib(n):
    if n <= 2:
        return 1
    return fib(n - 1) + fib(n - 2)

# The same numbers with a loop: n steps
def fib_loop(n):
    older, old = 1, 1
    for _ in range(n - 2):
        older, old = old, older + old
    return old

# Or remember answers you already have (memoization)
from functools import lru_cache

@lru_cache(maxsize=None)
def fib_fast(n):
    if n <= 2:
        return 1
    return fib_fast(n - 1) + fib_fast(n - 2)
  • When the recursive case calls itself twice on overlapping problems, the work doubles at every level. Use a loop or memoization.
  • Each call uses a stack frame. Python stops at about 1000 levels with RecursionError: maximum recursion depth exceeded; a loop would not.
  • Recursion shines when the problem is naturally nested: permutations, subsets, folders inside folders, trees, and “try every choice” searches.

Permutations and Towers of Hanoi

All permutations of a string

def permutations(word):
    if len(word) == 0:
        return [""]                   # one permutation of the empty string
    result = []
    for i in range(len(word)):
        shorter = word[:i] + word[i + 1:]
        for p in permutations(shorter):
            result.append(word[i] + p)
    return result

print(permutations("eat"))
# ['eat', 'eta', 'aet', 'ate', 'tea', 'tae']

Towers of Hanoi

def hanoi(n, source, target, spare):
    """Moves n disks from source to target using spare."""
    if n == 0:
        return
    hanoi(n - 1, source, spare, target)
    print(f"Move disk {n} from {source} to {target}")
    hanoi(n - 1, spare, target, source)

hanoi(3, "A", "C", "B")      # 7 moves; n disks take 2**n - 1

Mutual recursion is two functions that call each other, such as an expression evaluator where expression() calls term(), which calls factor(), which calls expression() again for a parenthesized part. The base case is still a function that returns without calling the other.

Sorting and Searching

Objects and Algorithms · Python 1

Selection Sort and Insertion Sort

Selection sort

def selection_sort(values):
    n = len(values)
    for i in range(n - 1):
        min_pos = i                           # find the smallest in values[i:]
        for j in range(i + 1, n):
            if values[j] < values[min_pos]:
                min_pos = j
        values[i], values[min_pos] = values[min_pos], values[i]   # swap it into place

Insertion sort

def insertion_sort(values):
    for i in range(1, len(values)):
        next_value = values[i]                # values[:i] is already sorted
        j = i
        while j > 0 and values[j - 1] > next_value:
            values[j] = values[j - 1]         # slide bigger ones right
            j -= 1
        values[j] = next_value                # drop it into the gap

Watch them work

Add print(f"pass {i + 1}: {values}") as the last line of the outer loop of selection sort (and print(f"pass {i}: {values}") in insertion sort) and run each on [11, 9, 17, 5, 12]:

selection sort           insertion sort
pass 1: [5, 9, 17, 11, 12]   pass 1: [9, 11, 17, 5, 12]
pass 2: [5, 9, 17, 11, 12]   pass 2: [9, 11, 17, 5, 12]
pass 3: [5, 9, 11, 17, 12]   pass 3: [5, 9, 11, 17, 12]
pass 4: [5, 9, 11, 12, 17]   pass 4: [5, 9, 11, 12, 17]

Selection sort grows the sorted part from the left by picking the smallest remaining value each pass; insertion sort grows it by sliding the next value into place. Both make about n²/2 comparisons: doubling the list quadruples the time. Insertion sort is fast on data that is already nearly sorted; selection sort always does the same work.

Mistakes to watch for

  • values = values.sort() leaves values as None; sort() works in place. And sorted(values) alone changes nothing unless you keep its result.
  • Mixing types: sorted([3, "a"]) gives TypeError: '<' not supported between instances of 'str' and 'int'. Convert the strings to numbers first, or pass key=str.
  • Inner loop starting at i instead of i + 1 in selection sort still works but compares each element with itself; starting the outer loop at 1 skips position 0 and leaves it unsorted.

Merge Sort

def merge_sort(values):
    if len(values) <= 1:
        return
    mid = len(values) // 2
    first = values[:mid]
    second = values[mid:]
    merge_sort(first)                 # sort each half
    merge_sort(second)
    merge(first, second, values)      # then merge them back into values

def merge(first, second, values):
    i = j = k = 0
    while i < len(first) and j < len(second):
        if first[i] < second[j]:
            values[k] = first[i]
            i += 1
        else:
            values[k] = second[j]
            j += 1
        k += 1
    while i < len(first):
        values[k] = first[i]; i += 1; k += 1
    while j < len(second):
        values[k] = second[j]; j += 1; k += 1
AlgorithmComparisons for n itemsBig-ODoubling n makes it
Selection sortabout n²/2O(n²)4 times slower
Insertion sortn²/4 average; n if already sortedO(n²)4 times slower
Merge sortabout n log2 nO(n log n)a little more than 2 times slower
Python’s sort (Timsort)n log n worst, n if already sortedO(n log n)a little more than 2 times slower
Linear searchn/2 average, n worstO(n)2 times slower
Binary search (sorted data)about log2 nO(log n)one more step

Big-O keeps only the fastest-growing term and drops constants: 3n² + 20n + 7 is O(n²). It describes how the work scales, not how many seconds it takes.

Searching

Linear search

def linear_search(values, target):
    for i in range(len(values)):
        if values[i] == target:
            return i
    return -1
# built in: target in values, or values.index(target)

Binary search (the list must be sorted)

def binary_search(values, target):
    low = 0
    high = len(values) - 1
    while low <= high:
        mid = (low + high) // 2
        if values[mid] == target:
            return mid
        elif values[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1
# 1,000,000 sorted items: at most 20 steps

The library does it faster: use these in real programs

values.sort()                                    # in place, ascending
values.sort(reverse=True)
new_list = sorted(values)                        # a sorted copy
names.sort(key=len)                              # by another rule
names.sort(key=str.lower)                        # case-insensitive
people.sort(key=lambda p: p.age)                 # objects, by one attribute
people.sort(key=lambda p: (p.last, p.first))     # by two

import bisect
pos = bisect.bisect_left(values, 42)             # binary search in the library

Sorting your own objects

class Country:
    def __init__(self, name, area):
        self.name = name
        self.area = area

    def __lt__(self, other):            # defines the natural order
        return self.area < other.area

countries.sort()                        # uses __lt__
countries.sort(key=lambda c: c.name)    # or any other order, by key

key vs __lt__

  • __lt__ in the class gives one natural order that sort(), sorted(), min() and max() all use.
  • A key function picks a different order for one call, without touching the class. It receives each item and returns what to compare.
  • Python’s sort is stable: items that compare equal keep their original order, so you can sort by last name after sorting by first name.