unfried.
Streak:0 days XP:0

Formula sheet

Python

94 entries in 12 units. Free to use and share.

Jump to a unit (12 units)

Unit 1 Values, types and arithmetic

Operator precedence

RankOperatorsGroups
1 (first)( )inside out
2**right to left
3* / // %left to right
4 (last)+ -left to right

Careful: A minus sign in front of a number ranks below **, so -2 ** 2 is −4. Write (-2) ** 2 to square −2. ^ is not a power in Python.

Taught in Arithmetic and precedence

Division, floor division and remainder

Also called integer division, modulo, mod.

a // b full groups of b fit in a, with a % b left over: 17 // 5 is 3 boxes and 17 % 5 is 2 eggs left.

7 / 2     # 3.5, always a float
7 // 2    # 3, rounds down
7 % 2     # 1, the remainder
-7 // 2   # -4, down, not toward 0

Careful: / gives a float even for an even division: 6 / 2 is 3.0. Floor division rounds down, so it differs from cutting off the decimals for negative numbers.

Taught in Three kinds of division

Types of values

type(x) names the type: print(type(3.0)) shows <class 'float'>.

TypeExamplesMade by
int42, -7, 0whole numbers; //, %, ** on ints
float42.0, 0.5, 4e2a decimal point or e; any /
str"42", "hello"quotes

Taught in Types: int, float and str

Strings with + and *

"3" + "4"    # "34", joined
"-" * 20     # 20 dashes, repeated
"3" + 4      # TypeError

Careful: + can join two strings or add two numbers, never one of each.

Taught in Types: int, float and str

Float precision and scientific notation

Also called floating point error, e notation.

A float keeps about 16 significant digits; most decimals are stored slightly off, so 0.1 + 0.2 is 0.30000000000000004. Halves and quarters are exact. Ints are exact at any size. 6.02e23 is 6.02 × 10²³ and 1e-6 is one millionth; a number written with e is a float.

Careful: Don't test computed floats with ==: 0.1 + 0.2 == 0.3 is False. Keep money as whole cents in ints.

Taught in Floats are close, not exact

print with several values

Commas separate the arguments; print puts sep (a space by default) between them and end (a new line by default) after the last. # starts a comment.

print("Mass:", 2.5, "kg")   # Mass: 2.5 kg
print(1, 2, 3, sep="-")     # 1-2-3
print("A", end="")          # no new line

Taught in Several values on one line

Reading a traceback

Also called error message.

Read the last line first, then the line number above it.

Last lineUsual cause
SyntaxErrora missing quote, comma or bracket; nothing runs
NameErrora word without quotes, or a misspelled name
TypeErroran operator given the wrong type, such as "3" + 4

Careful: The line named is where Python noticed the problem; the mistake can be on an earlier line.

Taught in Reading your first error message

Unit 2 Variables, assignment and input

Assignment

Python works out the expression on the right with the values variables hold at that moment, then stores the result under the name on the left.

name = expression

Careful: The name goes on the left: 5 = x is a SyntaxError. b = a copies the value once; a later change to a doesn't change b.

Taught in Assignment stores a value

Augmented assignment

Also called update a variable, increment.

The right side uses the old value, and the result replaces it. A variable holds only its latest value.

count += 1    # count = count + 1
balance -= 30 # balance = balance - 30
score *= 2    # score = score * 2

Taught in Updating a variable

Rules for names

Also called identifiers, variable names.

Letters, digits and underscores, not starting with a digit, with no spaces, and not a keyword (for, if, class, def…). Case matters, so total and Total are different names. Use meaningful snake_case names such as temp_c.

Careful: A name that was never assigned, or is spelled differently from where it was assigned, raises a NameError.

Taught in Names that work

Swapping two variables

The same swap in one line: a, b = b, a, which works out the right side before storing.

temp = a
a = b
b = temp

Careful: a = b followed by b = a does not swap: the first line overwrites a, and both end up with the old value of b.

Taught in Swapping two values

Reading a number

input() always returns a string. int() and float() convert it to a number.

n = int(input())    # a whole number
x = float(input())  # a decimal

Careful: int("3.5") raises a ValueError: read decimals with float(). int(3.9) is 3, because int() cuts off the decimal part instead of rounding.

Taught in input gives you a string

Read, compute, print

Read and convert the input, compute the result with brackets where the order needs them, then print it. This one converts °F to °C.

f = float(input())
c = (f - 32) * 5 / 9
print(c)

Taught in Read, compute, print

Unit 3 Strings and f-strings

String indexes

Also called indexing, character at a position.

Indexes run from 0 to len(s) - 1 from the left, and from −1 to -len(s) from the right.

s = "python"
s[0]        # "p", the first
s[-1]       # "n", the last
len(s)      # 6
s[len(s)]   # IndexError

Careful: Counting starts at 0, so s[1] is the second character and s[len(s)] is past the end.

Taught in Characters by position

String slices

Also called slicing, substring.

s[a:b] has the characters from index a up to, not including, b: b - a of them. A missing a means the start, a missing b the end.

s = "python"
s[1:4]   # "yth"
s[:2]    # "py"
s[2:]    # "thon"
s[-3:]   # "hon"

Careful: The stop index is left out. A slice past the end gives what is there; only a single index past the end is an error.

Taught in Slices

Strings are immutable

No string ever changes. Methods return a new string, which a line must assign to keep.

s.upper()          # result thrown away
s = s.upper()      # keeps it
s[0] = "E"         # TypeError
s = "E" + s[1:]    # builds a new string

Careful: A method call on its own line changes nothing that you can see.

Taught in Strings don't change

Common string methods

CallReturns
s.find(t)first index of t, or −1
s.count(t)how many times t appears
s.startswith(t)True or False
s.strip()copy without spaces at the ends
s.lower(), s.upper()copy in one case
s.replace(old, new)copy with every old swapped
s.split(",")list of the pieces
"-".join(pieces)one string, - between

Careful: Every method returns a new value; none changes s.

Taught in String methods

Comparing strings

Also called string order, alphabetical order.

Character by character from the left, by character code: digits, then capitals, then lowercase. A string that runs out first is the smaller.

"10" < "9"          # True
"Zebra" < "apple"   # True
"cat" < "catalog"   # True
"ell" in "hello"    # True

Careful: Text order is not number order. Convert with int() to compare numbers, and lowercase both sides to ignore case.

Taught in Comparing strings

f-strings

Also called formatted string, string interpolation.

Each expression in braces is worked out and inserted as text, numbers included.

name = "Ada"
f"Hello, {name}"   # "Hello, Ada"
f"{2 * 3} eggs"    # "6 eggs"
"Hello, {name}"    # braces kept

Careful: Without the f before the quote, the braces print as they are.

Taught in f-strings

Format specifications

Also called format spec, decimal places, padding.

The width is the total number of characters; the digit after the point is the decimals, rounded.

SpecValueText
{x:.2f}3.141593.14
{x:6.1f}98.6two spaces, 98.6
{n:>3}7two spaces, 7
{s:<4}"ab"ab, two spaces
{n:,}12345671,234,567

Careful: A spec changes only the printed text. The variable keeps its full value.

Taught in Format specifications

Building text

Also called escape sequences, concatenation.

\n is a new line, \t a tab, \" a double quote and \\ a backslash; each is one character.

"ab" + "c"         # "abc"
"=" * 3            # "==="
"Score: " + str(9) # "Score: 9"
"a\nb"             # 3 characters

Careful: + joins only strings: "Score: " + 9 is a TypeError. Use str() or an f-string.

Taught in Building text

Unit 4 Decisions

Comparison operators

Also called relational operators, Boolean expressions.

Every comparison gives True or False, a value of type bool.

OperatorTrue when
==the values are equal (5 == 5.0 is True)
!=the values differ
< and >strictly less, strictly greater
<= and >=less or equal, greater or equal

Careful: A single = stores and never compares; if x = 5: is a SyntaxError.

Taught in True or False

if and its block

Also called indentation, if statement.

The lines indented one level (four spaces) under the if run only when the condition is True. The first line back at the if's level runs either way.

if temp < 0:
    print("freezing")
print("done")

Careful: Indentation is part of the program. A line indented into the block runs only when the test passes; an if with no indented line is an IndentationError.

Taught in if and the indented block

if and else

else: lines up with its if, takes no condition and runs when the condition is False. Exactly one of the two blocks runs.

if n % 2 == 0:
    print("even")
else:
    print("odd")

Careful: Two separate if statements are two decisions, and each one is tested.

Taught in if and else

elif chain

Also called if elif else, multi-way decision.

Python tries the tests from the top and runs only the first True one. The else runs when none was True.

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("F")

Careful: With overlapping thresholds, test the strictest first. In the order >= 80 then >= 90, a score of 95 stops at the first test.

Taught in elif chains and their order

Logical operators

Also called and, or, not, chained comparison.

not goes first, then and, then or, unless brackets say otherwise.

ExpressionTrue when
a and bboth are True
a or bat least one is True
not aa is False
0 <= x <= 1000 <= x and x <= 100

Careful: Each side of or is its own condition: x == 1 or 2 is always True. Write x == 1 or x == 2.

Taught in and, or, not

Nested if

The inner if is tested only when the outer test passes. if a: with if b: inside does the same as if a and b:.

if age < 18:
    price = 5
else:
    if student:
        price = 8
    else:
        price = 12

Careful: An else pairs with the if at its own indentation, not with the nearest if above it.

Taught in Nested decisions

Truthy and falsy values

Also called truthiness.

0, 0.0, the empty string "", the empty list [] and None count as false in a condition. Every other value counts as true, so if name: asks whether name is non-empty.

Careful: "0", " " and [0] are not empty, so they are truthy.

Taught in Truthiness and float comparisons

Comparing floats with a tolerance

Also called float equality.

Computed floats carry rounding error (0.1 + 0.2 is 0.30000000000000004), so count them as equal when they differ by less than a small tolerance.

if abs(a - b) < 1e-9:
    print("equal")

Careful: a == b on computed floats is usually False even when exact arithmetic says they are equal.

Taught in Truthiness and float comparisons

Unit 5 While loops

While loop

The condition is tested before each iteration. While it is True the block runs; the first False test ends the loop. This one prints 3, 2, 1.

n = 3
while n > 0:
    print(n)
    n -= 1

Careful: The test comes only at the top, so a line that makes the condition False doesn't stop the rest of the block. A loop whose first test is False runs zero times.

Taught in Repeat while a condition holds

Running total

Also called accumulator, sum in a loop.

Set the accumulator once before the loop (0 for a sum, 1 for a product), update it inside, and use it after the loop.

total = 0
i = 1
while i <= n:
    total += i
    i += 1
print(total)

Careful: total = 0 inside the loop resets it every iteration, leaving only the last value. A product that starts at 0 stays 0.

Taught in Counters and running totals

Infinite loop

Also called loop never ends.

A loop never ends when nothing in its block moves the condition toward False. The usual causes are a missing update, an update to the wrong variable or in the wrong direction, and a != target the values step over.

Careful: The while line never changes a variable. On a computer, Ctrl+C stops a runaway program; this app stops it and says it never finished.

Taught in Loops that never end, and never start

Sentinel loop

Also called read until done, read input until a stop value.

Read one line before the loop, test it, process it, and read the next line as the last line of the block. The sentinel is tested before it can be processed. Set total = 0 before the first line.

line = input()
while line != "done":
    total += int(line)
    line = input()

Careful: input() returns a string: convert with int() before adding, and compare the sentinel as a string ("0" is not 0).

Taught in Read until done

break and continue

break ends the loop at once and goes to the first line after it. continue skips the rest of the block and goes back to the test. This loop adds the readings up to a 0 and skips the negative ones.

while True:
    r = int(input())
    if r == 0:
        break
    if r < 0:
        continue
    total += r

Careful: A continue that jumps past the update makes the loop endless; update first. Neither keyword ends the program.

Taught in break and continue

Off-by-one check

Also called fencepost error, loop runs once too often.

Check the first iteration (the start value) and the last (the value that makes the test fail). Starting at 1, while i <= n: runs n times for 1 to n; starting at 0, while i < n: runs n times for 0 to n − 1.

Careful: < never runs for its bound: while i < 10: stops before 10.

Taught in Off by one

Loop until a threshold

Also called years to double, count the steps.

Keep going while the value is short of the target, move it each iteration and count. At rate = 0.07 it prints 11.

money = 1000
years = 0
while money < 2000:
    money *= 1 + rate
    years += 1
print(years)

Careful: The loop ends only if the block carries the value across; at rate = 0 it never ends. For floats, test a tolerance such as abs(x * x - 2) > 0.01, not an exact value.

Taught in Loop until it's close enough

Unit 6 For loops and range

for loop over a sequence

Also called for each, loop variable, iterate over a string.

The block runs once per item, in order, with the loop variable assigned the next item before each run. After the loop the variable holds the last item.

for ch in "egg":
    print(ch)

Taught in For each item

range(n) and range(a, b)

Also called range, loop a fixed number of times.

range(a, b) starts at a and stops before b, so it holds b - a numbers. range(n) starts at 0.

RangeValuesHow many
range(4)0, 1, 2, 34
range(1, 5)1, 2, 3, 45 − 1 = 4
range(1, n + 1)1 to nn

Careful: The stop is never included: range(1, n) ends at n - 1. Stop at n + 1 to include n.

Taught in range

range with a step

Also called counting down, negative step, range(start, stop, step).

The step is added each time; the range ends at the last value before the stop.

RangeValues
range(0, 10, 3)0, 3, 6, 9
range(2, 21, 2)2, 4, …, 20
range(5, 0, -1)5, 4, 3, 2, 1

Careful: range(5, 0) is empty: without a negative step a range counts up. Counting down to 1 needs a stop of 0.

Taught in Steps and counting down

Total or count with a for loop

Also called accumulator, running total, counter.

Set up once before the loop, update in the block, print after the loop. A product starts at 1 and uses *=.

count = 0
for k in range(1, n):
    if k % 3 == 0:
        count += 1
print(count)

Careful: A count = 0 or total = 0 inside the loop resets it on every pass, so only the last pass counts.

Taught in Totals and counts with for

for or while

Also called choosing a loop.

Use for when the items or the number of runs are known before the loop starts (each letter, 10 rows, 1 to n). Use while when the loop stops on something found out as it runs (a sentinel, a threshold such as money doubling).

Careful: Assigning the loop variable inside a for block doesn't end the loop or skip values; the range hands out its next value anyway.

Taught in for or while

Nested loops

Also called loop inside a loop, grid, times table.

The inner loop runs all the way through for each pass of the outer loop, so the inner block runs (outer count) × (inner count) times.

for i in range(1, n + 1):
    for j in range(1, n + 1):
        print(i * j, end=" ")
    print()

Careful: The counts multiply, not add: 3 rows of 4 is 12. print() that ends a row goes in the outer block, one level in.

Taught in Loops inside loops

Table of values

Also called aligned columns, conversion table.

The heading goes before the loop, one row per value inside it, and any total after it. Field widths line up the columns.

print("   C      F")
for c in range(0, 101, 20):
    f = c * 9 / 5 + 32
    print(f"{c:>4} {f:6.1f}")

Careful: A heading or total indented into the loop prints once per row.

Taught in Tables of values

Unit 7 Functions

Defining and calling a function

Also called def, function call.

def stores the body under the name and runs nothing. Each call, the name with brackets, runs the whole body once.

def greet():
    print("hi")

greet()
greet()

Careful: The bare name greet without brackets calls nothing, and a call written above its def raises a NameError.

Taught in Define, then call

Parameters and arguments

Also called passing arguments, positional arguments.

Parameters are the names in the def; arguments are the values in the call. The first argument goes into the first parameter, and an argument can be any expression.

def area(w, h):
    return w * h

area(width, 4)

Careful: The caller's variable names don't have to match the parameters, and a missing argument is a TypeError.

Taught in Parameters and arguments

return against print

Also called return value, None.

return ends the call at once; lines after it never run.

In the bodyWhat the caller gets
return x * xthe value, to store, use or print
print(x * x)None (the text only appears on screen)
no returnNone

Careful: A returned value is not printed on its own. Write print(f(x)) to see it.

Taught in return, not print

Using a return value

Also called predicate, nested calls.

A call can go anywhere a value can: in a sum, an assignment, an if or another call. Inner calls run first. A predicate returns True or False.

def is_even(n):
    return n % 2 == 0

if is_even(k):
    print(double(double(k)))

Careful: if is_even: without brackets is always true, because the function itself counts as true.

Taught in Using what comes back

Local variables and scope

Also called UnboundLocalError, global variable.

Parameters and names assigned in a function are local to each call. A function can read an outside name it never assigns.

count = 0

def tally(count):
    return count + 1

count = tally(count)

Careful: Assigning to an outside name inside a function makes it local, so count = count + 1 there raises UnboundLocalError. Pass the value in and return the new one.

Taught in Scope: names inside a function

Default and keyword arguments

Also called optional parameters, named arguments.

A default is used when the call leaves the parameter out. A keyword argument names the parameter it fills, in any order.

def power(x, n=2):
    return x ** n

power(3)          # 9
power(n=3, x=2)   # 8

Careful: A parameter with a default can't come before one without, and every parameter with no default still needs a value.

Taught in Defaults, keywords and docstrings

Docstring

A string in triple quotes on the first line of the body says what the function does. help(area) shows it.

def area(w, h):
    """Return the area of a w by h rectangle."""
    return w * h

Careful: A docstring is never printed when the function runs.

Taught in Defaults, keywords and docstrings

Decomposition

Also called breaking a program into functions.

Give each job its own small function that returns its result, test each one on its own, and keep a short main part that calls them in order and prints.

Careful: A function that prints its result instead of returning it hands None to the next step.

Taught in Break it into functions

The call stack

Also called functions calling functions.

When one function calls another, the caller pauses at the call and the new call runs on top with its own local names. When it returns, the caller carries on from where it paused, using the returned value.

Careful: The two calls never share local names, even when they are spelled the same.

Taught in Functions calling functions

Unit 8 Lists

List indexes and slices

Also called indexing, list slicing.

Indexes run from 0 to len(a) - 1, or from −1 at the end. A slice is a new list that stops before its stop index.

temps = [18, 23, 19, 21]
temps[0]          # 18, the first
temps[-1]         # 21, the last
temps[1:3]        # [23, 19]
temps[len(temps)] # IndexError

Careful: Counting starts at 0, so a[len(a)] is past the end. The last element is a[-1] or a[len(a) - 1].

Taught in Lists and indexes

len, min, max, sum and the average

These functions read a list of numbers and return a value; the list is unchanged.

len(temps)                # 4
max(temps), min(temps)    # 23, 18
sum(temps) / len(temps)   # 20.25

Careful: The average divides by len, which is 0 for an empty list: test for that first.

Taught in Lists and indexes

Changing a list in place

Also called list methods, append, insert, pop, remove, mutable.

Lists are mutable: these change the list itself. Strings are immutable, so s[0] = "E" is a TypeError.

LineEffect
a[i] = xreplaces the element at index i
a.append(x)adds x at the end
a.insert(i, x)puts x at index i
a.pop()removes and returns the last element
a.remove(x)deletes the first element equal to x

Careful: a[i] = x only replaces an element that exists; it can't add one. remove takes a value, pop an index.

Taught in Lists change

Changing every element with a loop

Loop over the indexes and assign a[i] to replace each element in place.

for i in range(len(a)):
    a[i] = a[i] * 2

Careful: for x in a: x = x * 2 changes only the loop variable; the list keeps its values.

Taught in Looping over a list

enumerate

Hands the loop a count, starting at the second argument, and the element together.

for k, item in enumerate(menu, 1):
    print(f"{k}. {item}")

Careful: With no second argument the count starts at 0.

Taught in Looping over a list

Methods that return None

Also called sort vs sorted, a = a.sort().

Call a method that changes the list on a line of its own, and keep using the list.

Changes the list, returns NoneReturns a value, list unchanged
a.sort()sorted(a)
a.append(x)len(a)
a.reverse()max(a), min(a), sum(a)

Careful: a = a.sort() and a = a.append(x) replace the list with None.

Taught in Methods that return None

Aliasing and copying a list

Also called alias, copy, b = a.

Assignment never copies. A change through an alias shows through every name for that list; a copy is separate. b is a asks whether two names refer to one list.

b = a          # alias: one list, two names
c = a.copy()   # copy: a new list
c = a[:]       # also a copy
c = list(a)    # also a copy

Careful: Assigning a new list, a = [7, 8], moves only the name a; b keeps the old list.

Taught in Two names, one list

Lists passed to functions

Also called side effect, mutating an argument.

A parameter names the caller's list. Changing that list is a side effect the caller sees; assigning the parameter a new list is not.

def add_one(lst):
    lst.append(1)      # caller sees it

def add_one_new(lst):
    lst = lst + [1]    # local name only

Careful: To leave the argument unchanged, build a new list and return it.

Taught in Lists and functions

List comprehension

Also called building a list, split and convert.

The expression comes first, then the for, then an optional if that keeps only some items. It builds the same list as a loop that appends.

nums = [int(p) for p in "3,5,8".split(",")]
kept = [x for x in data if x > 0]

Careful: split returns strings; convert each piece before doing arithmetic.

Taught in Building lists

Nested lists (tables)

Also called list of lists, 2D list, grid.

The first index picks a row and the second a position in it. len(grid) counts rows.

grid = [[2, 4, 1], [3, 0, 5]]
grid[1][2]                     # 5: row 1, column 2
rows = [[0] * 3 for _ in range(3)]

Careful: [[0] * 3] * 3 holds one row three times, so a change to one row shows in all of them.

Taught in Lists of lists

Unit 9 Dictionaries, tuples and sets

Tuple packing and unpacking

Also called multiple assignment, return several values, swap.

Commas make a tuple, and names on the left of = take its values in order: q is 3 and r is 2. A function returns several values as one tuple.

q, r = divmod(17, 5)
a, b = b, a
return lo, hi

Careful: The number of names must match the number of values, or Python raises a ValueError. A tuple can't be changed: t[0] = 5 is a TypeError.

Taught in Tuples and unpacking

Dictionary lookup

Also called dict, key, KeyError, in.

Values are found by key. d[key] = value adds a new key or replaces the value of one that is there; each key appears once. key in d checks the keys.

density = {"water": 1.00,
           "ethanol": 0.789}
print(density["water"])
density["water"] = 0.998
print("water" in density)

Careful: A dictionary has no positions: d[0] looks for the key 0 and raises a KeyError if it isn't there.

Taught in Look it up by key

Counting with get

Also called frequency count, tally, dict.get.

d.get(k, 0) returns the value for k, or 0 when k isn't a key, so each new word starts at 0.

counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1

Careful: counts[w] += 1 alone raises a KeyError the first time a word appears. Set counts = {} up before the loop, not inside it.

Taught in Counting with a dictionary

Looping over a dictionary in order

Also called items, values, sorted keys.

d.items() gives the (key, value) pairs and d.values() the values. sorted(d) is the keys in order, and max(d, key=d.get) the key with the largest value.

for k in sorted(d):
    print(k, d[k])
for k, v in sorted(d.items()):
    print(k, v)
total = sum(d.values())

Careful: Standard Python keeps keys in the order they were added; other runtimes keep their own order, and none sort. When the order reaches the output, choose it with sorted.

Taught in Looping over a dictionary

Lookup table

Also called conversion table, table of constants.

One lookup replaces an if/elif chain, and a new entry extends it. An inch is exactly 0.0254 m and a foot 0.3048 m.

FACTORS = {"km": 1000, "cm": 0.01,
           "in": 0.0254,
           "ft": 0.3048}
meters = value * FACTORS[unit]

Careful: A unit missing from the table raises a KeyError; check with unit in FACTORS when a user types it.

Taught in Lookup tables

Set operations

Also called union, intersection, difference, remove duplicates.

A set has no order and no index. Print one through sorted(s), which gives a list in order.

ExpressionGives
set(values)each value once
x in swhether s holds x
a \| bvalues in either set
a & bvalues in both sets
a - bvalues in a but not in b

Careful: {} is an empty dictionary; an empty set is set().

Taught in Sets

Choosing a data structure

Also called list, tuple, dictionary, set.

Use a list for an ordered collection that grows, a tuple for a fixed group, a dictionary to find values by name, and a set when each value counts once.

StructureRepeatsCan changeFind by
listyesyesposition
tupleyesnoposition
dictionarykeys noyeskey
setnoyesin only

Taught in Which structure?

Unit 10 Patterns that solve problems

Accumulator plan

Also called running total, product of a list, join strings, start value.

Set the result up before the loop, update it inside, report it after. Start values: 0 for a sum, 1 for a product, "" for joined text, [] for a list.

def product(values):
    result = 1
    for v in values:
        result = result * v
    return result

Careful: A product started at 0 stays 0, and a set-up line indented inside the loop resets the result on every pass.

Taught in Accumulate

Count and filter

Also called count matching items, keep items that pass, filter comprehension.

The if decides which items count or are kept. One line: [x for x in values if x > limit]. The original list is unchanged.

count = 0
kept = []
for x in values:
    if x > limit:
        count += 1
        kept.append(x)

Careful: Decide whether a value equal to the limit passes (> or >=), and test that case.

Taught in Count and filter

Linear search

Also called find the index, first match, any, return -1.

A match returns at once from inside the loop. "Not found" is decided after the loop, once every item has failed.

def find(values, target):
    for i in range(len(values)):
        if values[i] == target:
            return i
    return -1

Careful: return -1 in an else inside the loop gives up after the first item that doesn't match.

Taught in Search

Best so far (maximum, minimum and where)

Also called largest, smallest, index of the maximum, argmax.

Start from the first item (best = xs[0] or best_i = 0). Strict > keeps the first of equal items; >= keeps the last.

best_i = 0
for i in range(len(xs)):
    if xs[i] > xs[best_i]:
        best_i = i

Careful: Starting at 0 returns 0 when no item beats it, as with all-negative readings. An empty list has no best.

Taught in Best so far

Transform

Also called map, convert every item, comprehension.

One new value per item, in order, in a new list. The loop form appends c_to_f(c) for each c to an empty list.

f = [c_to_f(c) for c in temps]

Careful: Assigning the loop variable (c = c_to_f(c)) stores nothing; assigning temps[i] overwrites the original list.

Taught in Transform

Rainfall (sentinel, filter, guarded average)

Also called average until a sentinel, average of valid readings, no data.

Test for the end marker before adding, filter the valid values, and report once after the loop.

total = 0
count = 0
for v in data:
    if v == 99999:
        break
    if v >= 0:
        total += v
        count += 1
if count == 0:
    print("no data")
else:
    print(total / count)

Careful: Without the count == 0 guard, a log with no valid readings divides by zero.

Taught in Combine the plans

zip and parallel lists

Also called two lists together, pair by position.

names[i] goes with scores[i]. zip hands out one item of each list per pass and stops at the end of the shorter list.

for n, s in zip(names, scores):
    print(n, s)

Careful: A value from one list is not an index into the other. Find the index of the best score, then use names[best_i].

Taught in Two lists side by side

Unit 11 Errors, debugging and testing

Reading a traceback

Also called stack trace, error message.

Read from the bottom. The last line is the exception's type and message. The File line above it is the line that was running. Each File line higher up is a call that led there, oldest at the top.

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(average(readings))
  File "main.py", line 3, in average
    return total / len(nums)
ZeroDivisionError: division by zero

Careful: The line named is where Python noticed the problem. The cause can be earlier, often a bad value passed in by the caller.

Taught in Read a traceback

Common exception types

Also called error types, built-in exceptions.

TypeUsual cause
NameErrora name never assigned, or misspelled
TypeErroran operation that can't take that type: "3" + 4
ValueErrorright type, unusable value: int("3.5")
IndexErroran index past the end of a list or string
KeyErrora key the dictionary doesn't have
ZeroDivisionErrordividing or % by 0
AttributeErrora method the type doesn't have
IndentationErrora missing or unexpected indent

Careful: The app's Run button words some messages a little differently from standard Python. The type is the same.

Taught in The common errors

Logic errors and debug prints

Also called wrong output, debugging.

A logic error raises nothing; the result is wrong. Work a small input by hand and print the variables you're unsure of, labeled. The first value that differs from yours is next to the bug.

for n in nums:
    total += n
    count += 1
    print("n", n, "count", count)

Careful: No traceback doesn't mean the program is right. Remove debug prints once the bug is fixed.

Taught in It runs, but it's wrong

Debugging with a hypothesis

Also called testing a guess.

Guess a cause that explains the wrong result, pick an input where the guess predicts a result different from the right one, run it, and keep the guess only if the prediction comes true.

Careful: An input where the guess and a correct function agree tests nothing. Undo a change that didn't help.

Taught in Debug by testing a guess

try and except

Also called exception handling, catching errors.

If a line in the try block raises the type named by except, the rest of the try block is skipped and the except block runs. The program then carries on after it.

try:
    n = int(text)
except ValueError:
    print("not a number")

Careful: A bare except: catches every exception, typos included, and hides them. Name the type and keep the try block around the line that can fail.

Taught in try and except

assert

Also called assertion, test case, AssertionError.

When the condition is True, nothing happens. When it is False, Python raises AssertionError with the message after the comma.

assert c_to_f(100) == 212.0, "boiling"
print("all tests passed")

Careful: Passing tests show only that those inputs work. Choose cases a wrong version would fail.

Taught in Test with assert

Choosing test cases

Also called edge cases, boundary values.

Add one typical case to these edge cases.

TestCatches
the boundary value (18 for >= 18)> written for >=
an empty lista division by its length
one itema count starting at 1
only negative numbersa maximum starting at 0

Careful: Typical cases alone rarely tell a right function from a near miss.

Taught in Tests that tell right from wrong

raise

Also called raising an exception, ValueError for bad input.

raise stops the function and every waiting call until an except for that type handles it. In the caller, except ValueError as e: keeps the exception, and print(e) shows its message.

def sqrt_of(x):
    if x < 0:
        raise ValueError("negative")
    return x ** 0.5

Careful: Returning a made-up value such as 0 or −1 for bad input lets the caller treat it as a real answer.

Taught in Raise an error on bad input

Unit 12 Numerical problems for engineers

Conversion table

Also called table of values, unit conversion loop.

The function converts at full precision, the heading prints once before the loop, and the format spec rounds only the printed text.

def psi_to_kpa(p):
    return p * 6.894757
print(" psi      kPa")
for p in range(0, top + 1, 20):
    kpa = psi_to_kpa(p)
    print(f"{p:>4} {kpa:8.2f}")

Careful: A format spec doesn't change the variable. To round a stored value you would have to assign it, and a table never needs to.

Taught in Conversion tables

Running average

Also called running mean, cumulative average.

Divide by the count so far, not by the length of the whole list. The last running average is the mean of all the readings.

total = 0
n = 0
for t in temps:
    total += t
    n += 1
    print(f"{total / n:.3f}")

Careful: The mean of an empty list divides by zero. Check the length first and report no data.

Taught in Averages that keep running

Standard deviation

Also called population standard deviation, spread.

σ
standard deviation
n
number of readings
xi
the readings
m
their mean

Applies: Dividing by n gives the population standard deviation, as math.sqrt(sum([(x - m) ** 2 for x in xs]) / len(xs)).

Careful: For a sample from something larger, divide by n−1 instead; a statistics course or lab handout says which.

Taught in Averages that keep running

Stopping a float loop

Also called float equality, tolerance, rounding error.

Count steps with an integer and compute each time, for k in range(n + 1): with t = k * dt, or stop on a tolerance, while abs(new - old) > 1e-9:.

Careful: Never stop on == or != with a computed float: ten additions of 0.1 give 0.9999999999999999, so while t != 1.0: never ends.

Taught in Floats in loops

Bisection

Also called interval halving, bisection method, root finding.

The sign change must be there at the start: f(lo) and f(hi) of opposite signs. After n halvings the width is the starting width divided by 2n⁠; 20 halvings shrink it about a million times.

def bisect(f, lo, hi):
    while hi - lo > 1e-6:
        mid = (lo + hi) / 2
        if f(lo) * f(mid) <= 0:
            hi = mid
        else:
            lo = mid
    return (lo + hi) / 2

Careful: The product test works for rising and falling functions alike; if f(mid) > 0: assumes the function rises. A tolerance below about 1e-15 times the root can never be met in floats.

Taught in Bisection

Newton's method

Also called Newton-Raphson, tangent line method.

x
the current guess
xnew
the next guess
f(x)
the function whose root is sought
f′(x)
its slope (derivative) at the guess

Applies: Repeat until a step is smaller than a tolerance, while abs(step) > 1e-12:. Near a root the correct digits roughly double each step.

Careful: It fails where f′(x)=0 (division by zero) and can cycle from a bad start, as x3−2x+2 does from 0. Bisection is slower but always closes in.

Taught in Newton's method

Euler's method

Also called Euler step, step-by-step simulation, time stepping.

y
the simulated quantity
ynew
its value one step later
r(y)
its rate of change, worked out at the start of the step
Δt
the time step (dt)

Applies: Loop round(total_time / dt) times with an integer count. Smaller steps bring the result closer to the exact answer, the error shrinking roughly in proportion to Δt⁠.

Careful: A step that is too large gives nonsense, such as coffee cooled below room temperature in one step.

Taught in Step-by-step simulation

Seeded random numbers

Also called random.seed, randint, pseudo-random.

randint(1, 6) includes both ends; random() gives a float from 0 up to 1. The same seed gives the same sequence on the same Python, so a run can be repeated exactly.

import random
random.seed(7)
roll = random.randint(1, 6)
u = random.random()

Careful: The seed is not the first number. Another Python (a laptop's against this app's) gives different numbers for the same seed.

Taught in Chance with a seed

Monte Carlo estimate of π

Also called Monte Carlo, random sampling.

h
random points in the unit square with x2+y2≤1
n
all random points

Applies: The share of points inside the quarter circle is close to its area, π/4⁠.

Careful: The estimate is never exact, and its typical error shrinks like 1/n⁠, so 100 times the points gives about a tenth of the error.

Taught in Chance with a seed

Data pipeline order

Also called clean convert average, error readings.

Drop error readings first, then convert, then average, then print, with one small function per job. Check the list of good readings for emptiness before dividing.

Careful: A raw list of nothing but error codes is not empty, so checking the raw list lets the average divide by zero.

Taught in A small data pipeline