These are the basics that school tends to brush over and that everyone learning to program needs: the building blocks that every mainstream language shares, defined one at a time, each with the smallest example that shows it and the specific way beginners get it wrong. It also covers what actually happens between your source file and the CPU, why two programs that compute the same answer can run at very different speeds, and why Lisp, Python, C, OCaml, Go and Rust are closer to each other than they look.

It is written for CS students, recent graduates and self-taught developers. Python is the main teaching language because it reads close to plain steps. Go is the second, because it makes several ideas explicit that Python hides. C, Rust, OCaml and Lisp appear only where they do something differently.

Last verified: December 2026. Versions used: Python 3.13 (the current release is 3.15; the program outputs and error messages shown were also checked on 3.14 and a 3.15 pre-release and match, except the bytecode listing), Go 1.24 (the examples need Go 1.22 or later), GCC 13.3 on x86-64 Linux, Rust 1.97 (edition 2024). The OCaml and Common Lisp snippets were checked against the OCaml 5.4 manual and the Common Lisp HyperSpec but not run here.

Short snippets show only the lines that matter. Each one was run as part of a complete program, and the outputs in comments are real.

Coding is translation

Programming is two jobs that beginners try to do at the same time. The first job is working out the steps: what you have, what you want, and the exact sequence of small moves that gets you from one to the other. That sequence is an algorithm, a finite list of unambiguous steps that solves a problem. The second job is writing those steps down in a language a computer accepts. That part is translation.

When you sit in front of an empty editor and start typing before you know the steps, you are trying to discover the algorithm and translate it in the same moment. Every syntax error then feels like a thinking error, and every thinking error looks like a syntax problem. You cannot tell which of the two jobs is failing, so you change random things until the output looks right. Most beginner confusion comes from this, not from the language.

The fix is boring and it works: work out the steps first, away from the keyboard. Write them on a whiteboard or on paper in plain words, then walk a small example through them by hand. When the steps produce the right answer on paper, the code is a translation of something you already understand, and the only errors left are translation errors, which the compiler or interpreter will point at for you.

A whiteboard is the best tool you have, except for the marker. The board is big and cheap to erase. It also cannot autocomplete anything, so it forces you to think in steps instead of syntax. The marker is the part that runs dry halfway through your explanation.

For me the line is anything involving graph theory or complex manipulation of data structures. If I try to write that straight into an editor, I end up discovering the algorithm and fighting the syntax at the same time. On the board I draw the nodes, move the pointers by hand, and the code afterwards is just transcription.

Everything below is vocabulary for the translation step. The last section works one problem from whiteboard to code so you can see the whole process.

Values, variables, initialization and assignment

A value is a piece of data: 42, "web1", [1, 2, 3]. A variable is a name that refers to a value so you can use it later. (In C and Go it is more literally a named piece of memory that holds the value; in Python it is a label attached to an object. The difference matters below.)

Initialization gives a variable its first value at the moment it comes into existence. Assignment gives an existing variable a new value. In Python the two look identical, which is why the difference rarely gets pointed out:

count = 0            # initialization: the name count is created and bound to 0
count = count + 1    # assignment: count already exists and gets a new value
print(count)         # 1

Read = as “now refers to”, never as “equals”. count = count + 1 is nonsense in algebra and perfectly sensible as an instruction: take the current value, add one, make count refer to the result.

Other languages make the difference visible, and seeing it there helps in Python too. Go has two operators:

count := 0                // := declares a new variable and initializes it
count = 5                 // = assigns to a variable that already exists
var total int             // declared with no value: Go initializes it to the zero value, 0
fmt.Println(count, total) // 5 0

Go guarantees that a variable with no explicit value holds its type’s zero value (0, "", false, nil). C does not. A local variable in C that you declare without initializing holds an indeterminate value, whatever bits were already in that memory:

int count;         /* declared, not initialized: its value is indeterminate */
int total = 0;     /* initialized */
total = 5;         /* assigned */
printf("%d\n", count);   /* printed 32765 on the test machine; it could print anything */

GCC warns about it with -Wall ('count' is used uninitialized), but it still compiles, and the C standard makes no promise about what such a program does. Rust refuses to compile the same mistake (error[E0381]: used binding `count` isn't initialized). Rust also makes variables unchangeable by default: let limit = 10; can never be assigned again, and you write let mut count = 0; when you intend to change it.

C++ is where the distinction stops being academic. For a class type, initialization runs a constructor that builds a new object, while assignment runs operator= on an object that already exists. A const can be initialized but never assigned:

std::string name = "web1";   // initialization: a constructor builds a new string
name = "web2";               // assignment: operator= replaces the contents of an existing one
const int limit = 10;        // a const must be initialized here
// limit = 20;               // error: assignment of read-only variable 'limit'

Where beginners get confused

Two names, one value. In Python, assignment never copies. It makes a second name refer to the same object:

a = [1, 2, 3]
b = a                # b is a second name for the same list, not a copy
b.append(4)
print(a)             # [1, 2, 3, 4]

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

If you picture variables as boxes that hold values, this output is baffling. If you picture them as labels tied to objects, it is obvious: a and b are two labels on one list. Numbers and strings behave the same way, but you cannot change them in place (they are immutable), so the shared label never surprises you.

Go adds its own trap. Inside a new block, := declares a new variable even if one with the same name exists outside, so a typo of := for = silently creates a second variable:

limit := 10
if limit > 5 {
    limit := 20                  // := declares a second, inner limit that hides the outer one
    fmt.Println("inner:", limit) // inner: 20
}
fmt.Println("outer:", limit) // outer: 10

This is called shadowing. It compiles cleanly. If you meant to change the outer limit, use =.

Branching: if, else if, else

A branch runs one block of code or another depending on a condition, an expression that is either true or false.

def describe(temp_c):
    if temp_c < 0:
        return "freezing"
    elif temp_c < 15:
        return "cold"
    elif temp_c < 25:
        return "mild"
    else:
        return "hot"

The conditions are checked top to bottom and the first one that is true wins. Everything after it is skipped. Python spells “else if” as elif; Go, C and Rust write else if. Go and Rust require braces and do not want parentheses around the condition. Go and Rust also require the condition to be an actual boolean, so if count { ... } with an integer is a compile error, where C and Python would treat any nonzero number as true.

Where beginners get confused

Order matters, and a wrong order does not raise an error:

def grade(score):
    if score >= 60:
        return "D"
    elif score >= 90:      # never reached: any score of 90 or more already matched the line above
        return "A"
    else:
        return "F"

print(grade(95))   # D

The fix is to order the tests from most specific to least specific. On a whiteboard you would catch this in seconds by running one example through it. In an editor it ships.

Pattern matching

Pattern matching compares a value against a list of shapes and runs the code for the first shape that fits, pulling pieces of the value out into names as it goes. It is a branch that also takes the value apart.

Python has had it since 3.10 as the match statement:

import math

def area(shape):
    match shape:
        case ("circle", radius):
            return math.pi * radius * radius
        case ("rect", width, height):
            return width * height
        case _:
            raise ValueError(f"unknown shape: {shape}")

print(area(("circle", 1)))     # 3.141592653589793
print(area(("rect", 3, 4)))    # 12

case ("circle", radius) means: a two-item sequence whose first item is the string "circle"; bind the second item to radius. _ matches anything.

It is not a fancier switch. C’s switch compares one integer against constants and, without a break, falls through into the next case:

switch (level) {
case 1:
    printf("one\n");      /* no break: execution falls through into case 2 */
case 2:
    printf("two\n");
    break;
}
/* with level == 1 this prints "one" and then "two" */

Pattern matching is a staple of the ML family of languages, which includes OCaml, and Rust’s version follows that tradition. In Rust and OCaml the compiler checks that your cases cover every possibility. Leave one out and OCaml warns (warning 8), while Rust refuses to compile:

enum Shape {
    Circle(f64),
    Rect(f64, f64),
}

fn area(shape: Shape) -> f64 {
    match shape {
        Shape::Circle(radius) => std::f64::consts::PI * radius * radius,
        Shape::Rect(width, height) => width * height,
    }
}

Delete the Rect line and you get error[E0004]: non-exhaustive patterns: `Shape::Rect(_, _)` not covered. That check is why people who have used it miss it in other languages: add a new kind of shape and the compiler lists every place you forgot to handle it. Go has no pattern matching; its switch compares values and, unlike C’s, does not fall through by default. (A Go type switch can branch on which type a value has, but it does not take the value apart or check that you covered every case.)

Where beginners get confused

In Python, a bare name in a case is not a comparison. It is a capture pattern: it always matches and binds the value to that name.

LIMIT = 100
value = 7

match value:
    case LIMIT:                # captures: binds the name LIMIT to 7, always matches
        print("at the limit")

print(LIMIT)                   # 7

This prints at the limit and overwrites your constant. If you add a second case after it, Python refuses to run the file: SyntaxError: name capture 'LIMIT' makes remaining patterns unreachable. To compare against a constant, use a dotted name (config.LIMIT, Color.RED) or a guard: case x if x == LIMIT:.

Loops: for, while, do-while

A loop repeats a block of code. There are three shapes, and the difference is when the test happens.

A for loop runs once per item in a sequence. In Python that is the only kind of for there is:

for name in ["web1", "web2", "db1"]:   # once per item
    print(name)

for i in range(3):                     # range(3) produces 0, 1, 2
    print(i)

A while loop tests a condition first and repeats as long as it stays true. If the condition is false at the start, the body never runs:

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

A do-while loop runs the body first and tests afterward, so the body always runs at least once. That is the natural shape for “ask until the answer is valid”. C has it:

int n;
do {
    printf("Enter a number from 1 to 10: ");
    if (scanf("%d", &n) != 1) {
        return 1;
    }
} while (n < 1 || n > 10);   /* the test comes after the body */

Python, Go, Rust and OCaml have no do-while. The idiom in each is a loop with no condition and a break at the bottom:

while True:
    n = int(input("Enter a number from 1 to 10: "))
    if 1 <= n <= 10:
        break

Go has exactly one loop keyword, for, and covers every shape with it:

for i := 0; i < 3; i++ { // counting loop: init; condition; post
    fmt.Println(i)
}
for remaining > 0 { // what other languages spell "while"
    remaining--
}
for i, name := range []string{"web1", "db1"} { // once per item, with its index
    fmt.Println(i, name)
}
for i := range 3 { // Go 1.22 and later: 0, 1, 2
    fmt.Println(i)
}
for { // no condition: repeat until break; put the test at the bottom for do-while
    attempts++
    if attempts >= 3 {
        break
    }
}

Rust spells the unconditional loop loop { ... }.

Where beginners get confused

Changing a list while you loop over it:

numbers = [1, 2, 2, 3]
for n in numbers:
    if n == 2:
        numbers.remove(n)
print(numbers)    # [1, 2, 3]: one 2 survived

The loop walks the list by position. Removing the first 2 shifts everything left, so the second 2 moves into the slot the loop has already visited. Build a new list instead: numbers = [n for n in numbers if n != 2].

The other classic is the loop that never ends because nothing inside it changes the condition. Before you write a while, say out loud which variable moves toward making the condition false, and where.

Functions: parameters and arguments

A function is a named block of steps that takes inputs and gives back a result. You define it once and call it as often as you like.

A parameter is the name in the function’s definition. An argument is the value you pass in when you call it. People use the two words interchangeably; they are different things, and the difference explains the most common function confusion.

def power(base, exponent):        # base and exponent are parameters
    return base ** exponent

x = 10
y = 2
print(power(x, y))                # x and y supply the arguments: 100
print(power(2 + 8, 2))            # arguments are values; they do not need names: 100

Why the names do not have to match

When you call power(x, y), Python evaluates each argument expression to a value, then binds those values to the parameters by position: first value to the first parameter, second to the second. The names x and y never reach the function. Only the values do. Inside power, the values are known as base and exponent, because those are the names the function’s author chose.

The proof is what happens when the caller’s names collide with the parameter names in the wrong order:

exponent = 2
base = 10
print(power(exponent, base))      # 1024, not 100

The first argument evaluates to 2 and lands in the first parameter, base. The second evaluates to 10 and lands in exponent. 2 ** 10 is 1024. The matching spelling meant nothing.

Arguments are evaluated in the caller, then bound to parameters by position, regardless of their names The caller’s variable names stay in the caller. Only the values cross into the function, matched by position.

The second half of the reason is scope: the region of code where a name is visible. Each function call gets its own fresh set of local names. A parameter is a local name that starts out bound to an argument’s value. Names inside the function do not exist outside it, and the caller’s names are not what the function sees:

def power(base, exponent):
    result = base ** exponent
    return result

power(10, 2)
print(result)    # NameError: name 'result' is not defined

This separation is the point of a function. The author of power should not need to know what you called your variables, and you should not need to know what they called theirs.

When names do matter: keyword arguments

Python also lets you pass arguments by name. These are keyword arguments, and for them the spelling must match the parameter exactly:

print(power(exponent=2, base=10))   # 100: matched by name, so order no longer matters
print(power(x=10, exponent=2))      # TypeError: power() got an unexpected keyword argument 'x'

The rule in the Python reference is precise: positional arguments fill the parameter slots first, left to right, then each keyword argument fills the slot whose parameter has that name. Go, C and Rust have no keyword arguments; every call is positional.

Where beginners get confused

Mutating an argument versus rebinding a parameter. Because a parameter is a new name for the same object, changing the object is visible to the caller, but pointing the name at something else is not:

def add_item(items):
    items.append("new")       # changes the caller's list: same object, second name

def replace(items):
    items = ["replaced"]      # rebinds the local name only

basket = ["old"]
add_item(basket)
replace(basket)
print(basket)                 # ['old', 'new']

Go makes this explicit. Arguments are copied. If you want the function to change the caller’s value, you pass a pointer (its address) and say so in the type. (Slices and maps are the catch: copying one copies only a small header that still points at the same elements, so a function can change the caller’s elements without a pointer.)

type Point struct{ X, Y int }

func moveCopy(p Point)     { p.X = 99 } // p is a copy: the caller's Point is untouched
func movePointer(p *Point) { p.X = 99 } // p points at the caller's Point

a := Point{1, 2}
moveCopy(a)     // a.X is still 1
movePointer(&a) // a.X is now 99

Functions as values: first-class, higher-order, lambdas

In Python, Go, Rust, OCaml and Lisp, a function is a value like any other. You can store it in a variable, put it in a list, pass it to another function, or return it from one. A language where that is true has first-class functions.

A function that takes another function as an argument, or returns one, is a higher-order function. These two terms get mixed up constantly. First-class describes the language (functions are values). Higher-order describes a particular function (it works on other functions). A first-order function is the opposite of higher-order: it takes and returns plain data only.

def double(x):
    return x * 2

def apply_twice(f, x):                     # higher-order: f is a function
    return f(f(x))

operation = double                         # no parentheses: the function itself, not its result
print(operation(5))                        # 10
print(apply_twice(double, 5))              # 20

The parentheses are the whole difference. double is the function. double(5) calls it and is the number 10.

A lambda is a function without a name, written inline where you need it. In Python it is limited to a single expression:

print(apply_twice(lambda x: x + 3, 5))     # 11

servers = [{"name": "web1", "load": 0.9}, {"name": "db1", "load": 0.2}]
by_load = sorted(servers, key=lambda s: s["load"])
print([s["name"] for s in by_load])        # ['db1', 'web1']

sorted is higher-order: its key argument is a function that turns each item into the thing to sort by. That is where lambdas earn their place: a short function used once, right where it is used. Go writes them as func(x int) int { return x * 2 } and Rust as |x: i32| x * 2. If a lambda grows past one line of logic, give it a name with def.

Closures and factory functions

A closure is a function bundled with the variables it uses from the scope where it was created. Those variables stay alive as long as the function does, even after the scope that created them has finished.

def make_counter():
    count = 0

    def increment():
        nonlocal count        # assign to the captured variable instead of creating a new local
        count += 1
        return count

    return increment

a = make_counter()
b = make_counter()
print(a(), a(), a())    # 1 2 3
print(b())              # 1: b captured its own, separate count

make_counter has returned, so by ordinary rules its local count should be gone. It is not, because increment still refers to it. Each call to make_counter creates a new count and a new increment that holds on to it, which is why a and b count independently.

Two closures, each holding its own captured count variable Each call to make_counter leaves behind a function and the variable it captured. a and b never share a count.

Without nonlocal, count += 1 would make Python treat count as a brand-new local of increment, and the first call would fail with UnboundLocalError: cannot access local variable 'count' where it is not associated with a value. Python decides whether a name is local by looking for any assignment to it in the function body. Go has no such keyword; a Go closure can assign to captured variables directly:

func makeCounter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

A factory function is a function whose job is to build and return something: a configured function, or an object. make_counter is one. Here is the classic function-building version:

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

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))    # 20 30

In Go, factory functions that build structs are the normal way to construct things, and by convention they are named New plus the type. Note that the field count starts with a lowercase letter, so code in other packages cannot touch it except through the methods (more on that under exported names):

type Counter struct {
    count int
}

func NewCounter(start int) *Counter {
    return &Counter{count: start}
}

func (c *Counter) Next() int {
    c.count++
    return c.count
}

Where beginners get confused

A closure captures the variable, not the value it had at the time. Python looks the variable up when the function runs:

callbacks = []
for i in range(3):
    callbacks.append(lambda: i)
print([f() for f in callbacks])      # [2, 2, 2]

All three lambdas refer to the same i, and by the time they run the loop has finished and i is 2. The standard fix is a default argument, which is evaluated once when each lambda is created: lambda i=i: i gives [0, 1, 2].

Go had the same bug for years. Since Go 1.22, each iteration of a for loop gets its own copy of the loop variable, so the equivalent Go code prints 0 1 2, provided the go line in your go.mod says 1.22 or later. If you read Go code written before 2024, you will see i := i inside loops; that line was the workaround.

Python and Go closures always capture the variable itself, never a copy of its value. Rust and C++ let you choose. A Rust closure borrows the variables it uses unless it needs ownership or you write move, which moves (or, for simple types such as integers, copies) them into the closure. A C++ lambda lists its captures: [x] copies x when the lambda is created, [&x] refers to the caller’s x.

Classes and objects

A class is a template that bundles data with the functions that operate on that data. An object (or instance) is one value built from that template. A function defined inside a class is a method. This style of organizing code around objects is object-oriented programming.

class Rect:
    def __init__(self, width, height):   # runs when you create a Rect
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

r = Rect(3, 4)          # r is an object, an instance of Rect
print(r.area())         # 12

__init__ is the initializer, usually called the constructor: it runs once, right after the object is created, and initializes its data. self is the object the method was called on. r.area() is shorthand for Rect.area(r): Python passes the object as the first argument, and self is simply the conventional name for the first parameter. That is the same positional binding from the functions section, applied to methods.

Where beginners get confused

Forgetting self. If you write def area(): with no parameter, calling r.area() still passes r, and Python complains about the count: TypeError: Rect.area() takes 0 positional arguments but 1 was given. That error message only makes sense once you know about the hidden first argument.

Putting data on the class instead of the object. A variable assigned in the class body belongs to the class and is shared by every instance:

class Team:
    members = []                 # class attribute: one list shared by every Team

    def add(self, name):
        self.members.append(name)

a = Team()
b = Team()
a.add("Ada")
print(b.members)                 # ['Ada']

Per-object data goes in __init__ as self.members = [].

Inheritance and polymorphism

Inheritance lets one class start from another and add or replace pieces. The new class (the subclass) gets every method of the original (the base class or superclass) unless it defines its own. Defining your own version of an inherited method is overriding.

Polymorphism means code that works on values of different types through one shared interface, with each type supplying its own behavior. The caller writes shape.area() and does not know or care which kind of shape it has.

import math

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

    def area(self):
        raise NotImplementedError

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

class Circle(Shape):                      # a Circle is a Shape
    def __init__(self, radius):
        super().__init__("circle")        # run Shape's constructor first
        self.radius = radius

    def area(self):                       # overrides Shape.area
        return math.pi * self.radius ** 2

class Rect(Shape):
    def __init__(self, width, height):
        super().__init__("rectangle")
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

for shape in [Circle(1), Rect(3, 4)]:
    print(shape.describe())
circle with area 3.14
rectangle with area 12.00

describe is written once, in Shape. When it calls self.area(), Python looks up area on the actual object at run time, finds the Circle or Rect version, and runs that. Choosing the method based on the object’s real type at run time is called dynamic dispatch, and it is the machinery behind this kind of polymorphism, called subtype polymorphism. You will meet two other kinds: parametric polymorphism (generics, one function written once for any type, such as Go’s func Max[T cmp.Ordered](a, b T) T) and ad hoc polymorphism (overloading, one name with separate versions chosen by argument type, as in C++).

describe is inherited from Shape; its call to self.area dispatches to Circle or Rect depending on the object One describe method, two area methods. The object decides which area runs.

Inheritance is easy to overuse. A deep hierarchy couples every subclass to the details of every class above it, so a change near the top ripples down in ways that are hard to predict. The common advice, which I agree with, is to inherit only when the “is a” relationship is real and stable, and otherwise to build objects out of other objects (composition).

Composition and interfaces: Go and Rust

Go and Rust have no classes and no inheritance. They get polymorphism a different way: you describe a behavior as a set of method signatures, and any type that provides those methods can be used wherever that behavior is required.

In Go that description is an interface, and a type satisfies it implicitly, just by having the methods. There is no implements keyword:

type Shape interface {
    Area() float64
}

type Circle struct{ Radius float64 }
type Rect struct{ Width, Height float64 }

func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (r Rect) Area() float64   { return r.Width * r.Height }

func describe(s Shape) string {
    return fmt.Sprintf("%T with area %.2f", s, s.Area())
}

describe(Circle{1}) and describe(Rect{3, 4}) both work and print main.Circle with area 3.14 and main.Rect with area 12.00. For reuse, Go offers embedding: put one struct type inside another and the outer type gains the inner type’s methods. It looks like inheritance, but the outer type does not become the inner type; it only forwards to it.

Rust’s version is a trait. Unlike Go, you state explicitly that a type implements it, and a trait can carry default methods, which covers most of what people used inheritance for:

trait Shape {
    fn area(&self) -> f64;

    fn describe(&self) -> String {
        // default method: written once, shared by every type that implements Shape
        format!("shape with area {:.2}", self.area())
    }
}

struct Rect {
    width: f64,
    height: f64,
}

impl Shape for Rect {
    fn area(&self) -> f64 {
        self.width * self.height
    }
}

With a Circle implemented the same way, a Vec<Box<dyn Shape>> can hold circles and rectangles side by side, and calling describe() on each dispatches to the right area(), the same as the Python version. The difference is that the relationship is “can do” instead of “is a”, so a type can implement as many traits as it needs without a family tree.

Public and private, exported and non-exported

Every language gives you a way to mark which names are part of a component’s public face and which are internal details that outsiders should not depend on. Public names can be used from outside; private names cannot (or should not). The point is not secrecy. It is freedom to change the internals later without breaking anyone, because nobody outside was allowed to rely on them.

Each language draws the line differently:

Language How you mark it public Default Enforced by
Python no marker; a leading _ means “internal” everything is reachable convention only
Go name starts with an uppercase letter (exported) lowercase is package-private (non-exported) compiler
Rust pub keyword private to the module compiler
C declare it in a header for other files to use; static hides a function inside one .c file non-static functions are visible to the linker from any file compiler and linker (static only)
C++ public: / private: sections in a class members of a class are private compiler

Go’s rule surprises people coming from other languages because there is no keyword. geometry.Area is exported because it starts with a capital A. scaled is not, so code outside package geometry cannot call it:

package geometry

// Area is exported: its name starts with a capital letter.
func Area(width, height float64) float64 {
    return scaled(width) * height
}

// scaled is unexported: only code inside package geometry can call it.
func scaled(x float64) float64 {
    return x
}

The same rule applies to struct fields and methods, which is why Counter.count in the factory example is hidden and Counter.Next is not. “Exported” is the Go word; Rust and C++ say “public”. They mean the same thing at different granularities: Go draws the line at the package, Rust at the module, C++ at the class.

Rust marks public items with pub; everything else is private to its module and the modules nested inside it. Calling a private function from outside fails with error[E0603]: function `scaled` is private.

Python enforces nothing. A leading underscore tells readers “do not rely on this”, and that is all:

print(geometry._scaled(5))      # 5: Python does not stop you

Two leading underscores inside a class (self.__secret) trigger name mangling: Python renames the attribute to _ClassName__secret to avoid accidental clashes in subclasses. It is still reachable under the mangled name. It is not privacy, and the Python tutorial says as much.

Modules, packages and imports

Once a program outgrows one file you split it up. A module is a unit of code with its own namespace (its own set of top-level names). A package is a group of modules. An import makes another module’s public names available in the current file. The words mean slightly different things in different languages, and that mismatch is half the confusion.

In Python, a module is one .py file and a package is a directory of modules (traditionally with an __init__.py file in it). Importing a module runs its top-level code once and caches the result; later imports reuse the cached module:

# geometry.py
print("geometry is being loaded")

def area(width, height):
    return _scaled(width) * height

def _scaled(x):               # leading underscore: "internal, do not rely on this"
    return x

if __name__ == "__main__":    # true only when this file is run directly
    print(area(3, 4))
# main.py
import geometry
import geometry                 # second import: nothing runs, the cached module is reused
from geometry import area

print(geometry.area(3, 4))      # 12
print(area(3, 4))               # 12

Running python3 main.py prints geometry is being loaded exactly once. The __name__ == "__main__" check lets one file work both as an importable module and as a script.

In Go, the words are reversed from what Python users expect. A package is all the .go files in one directory, compiled together; every file in the directory starts with the same package line, and they can all see each other’s unexported names. A module is a collection of packages released together, defined by a go.mod file whose module line gives the module path. You import a package by its module path plus its directory:

elements/
├── go.mod              module example.com/elements
├── geometry/
│   └── geometry.go     package geometry
└── usegeo/
    └── main.go         package main
package main

import (
    "fmt"

    "example.com/elements/geometry"
)

func main() {
    fmt.Println(geometry.Area(3, 4)) // 12
}

Inside a module, the import path is the module path joined with the directory, and you call exported names through the package name: geometry.Area. Go refuses to compile a file that imports a package it does not use, which keeps import lists honest.

In Rust, a crate is the unit the compiler builds (a library or a program), a module is a namespace inside it declared with mod, and a package is one or more crates plus a Cargo.toml file, the thing Cargo (Rust’s build tool) builds and publishes. You bring names in with use.

Where beginners get confused

Naming your own file after a standard library module. Save a script as random.py and import random inside it, and Python finds your file first, because the directory containing the script you run sits at the front of the module search path:

AttributeError: module 'random' has no attribute 'randint' (consider renaming '.../random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

Python 3.13 added the hint in parentheses. Older versions give a less helpful message that does not mention the file name clash.

Dependency injection

Dependency injection means a piece of code receives the things it depends on from its caller instead of creating them itself. The term sounds like it needs a framework. In practice it is usually a function parameter.

Here is a function that decides whether to send an alert and builds its own mail sender:

class SmtpMailer:
    def send(self, to, body):
        ...  # connects to a real mail server

def alert_if_full(disk_percent):
    if disk_percent > 90:
        mailer = SmtpMailer()                      # the dependency is built in here
        mailer.send("ops@example.com", f"disk at {disk_percent}%")

The decision logic is one line, but you cannot test it without sending real email, because the function insists on creating a real SmtpMailer. Now pass the mailer in:

def alert_if_full(disk_percent, mailer):           # the dependency is passed in
    if disk_percent > 90:
        mailer.send("ops@example.com", f"disk at {disk_percent}%")

class FakeMailer:
    def __init__(self):
        self.sent = []

    def send(self, to, body):
        self.sent.append((to, body))

fake = FakeMailer()
alert_if_full(95, fake)
alert_if_full(50, fake)
assert fake.sent == [("ops@example.com", "disk at 95%")]

The function no longer knows or cares what kind of mailer it has. In production you pass an SmtpMailer. In a test you pass a FakeMailer that records what it was asked to send, and the test runs in microseconds with no network. That is the whole technique, and it is why code written this way is easier to test: every outside effect (network, disk, clock, database) arrives through a door you control.

In Go the door is an interface, and because Go interfaces are satisfied implicitly, the fake needs no declaration beyond having the right method:

type Mailer interface {
    Send(to, body string) error
}

func AlertIfFull(diskPercent int, m Mailer) error {
    if diskPercent > 90 {
        return m.Send("ops@example.com", fmt.Sprintf("disk at %d%%", diskPercent))
    }
    return nil
}

Frameworks that wire dependencies together automatically exist in most languages. You do not need one to do dependency injection, and I would learn it with plain parameters first so you can see what the framework is doing for you.

From source file to CPU

Your source file is plain text. The CPU understands neither text nor Python nor Go. It understands machine code: binary-encoded instructions such as “add these two registers” or “jump to this address if the last comparison was not equal”. Every language implementation exists to bridge that gap, and they all start the same way.

  1. Lexing (or scanning) reads characters and groups them into tokens: def, sum_to, (, n, ), :. Whitespace and comments mostly disappear here.
  2. Parsing arranges the tokens into a syntax tree that reflects the program’s structure: this function contains this loop, which contains this assignment. Syntax errors come from this stage.
  3. Analysis resolves which declaration each name refers to and, in statically typed languages, checks types. The tree is then usually lowered into an intermediate representation (IR), a simpler form that is easier to optimize and translate.
  4. Then the routes split.

On the ahead-of-time route (C, C++, Go, Rust, OCaml with ocamlopt), a compiler translates the IR all the way to machine code for a specific CPU family and writes object files. A linker combines your object files with library code into one executable. When you run it, the operating system’s loader maps the file into memory (for dynamically linked programs, a dynamic linker also loads the shared libraries it needs) and points the CPU at the first instruction.

On the bytecode route (CPython, Java, OCaml with ocamlc), the compiler emits bytecode: instructions for an imaginary machine. A program called a virtual machine (VM) reads those instructions one at a time and carries each out. The VM is itself an ordinary compiled program, so the CPU is running the VM’s machine code, and the VM is acting out your bytecode.

Source code goes through lexing, parsing and analysis, then either to machine code, linking and the OS loader, or to bytecode run by a virtual machine; both routes end on the CPU Every implementation shares the front half. The split is whether your program becomes machine code or bytecode for a VM.

This is why “Python is interpreted” is only half true. When you run python3 script.py, CPython (the standard implementation, written in C) compiles the whole file to bytecode first, then its VM runs that bytecode. For imported modules it caches the bytecode in __pycache__/ as .pyc files so the next run can skip compilation; the script you run directly is recompiled every time. Java uses the same two steps with a different VM (javac writes the bytecode ahead of time, the JVM runs it), and its VM also compiles hot bytecode to machine code while the program runs (just-in-time or JIT compilation). CPython has had an experimental JIT of its own since 3.13. As of 3.15 it is still experimental and off by default: the python.org Windows and macOS installers include it, and you turn it on with the environment variable PYTHON_JIT=1. Check the “What’s New” page for your version, because this is changing release by release. “Compiled” and “interpreted” describe implementations, not languages: OCaml ships both a bytecode compiler and a native one, and SBCL compiles Common Lisp to native code, including most of what you type at its prompt.

One function at three levels

Here is one small function, written in Python and C:

def sum_to(n):
    total = 0
    for i in range(1, n + 1):
        total += i
    return total
int sum_to(int n) {
    int total = 0;
    for (int i = 1; i <= n; i++) {
        total += i;
    }
    return total;
}

The dis module shows the bytecode CPython produced for the Python version. Save it as sum_to.py, laid out as import dis, two blank lines, the function, two blank lines, dis.dis(sum_to), then run it (the left column holds line numbers in that file, so it shifts if your layout differs):

python3 sum_to.py
  4           RESUME                   0

  5           LOAD_CONST               1 (0)
              STORE_FAST               1 (total)

  6           LOAD_GLOBAL              1 (range + NULL)
              LOAD_CONST               2 (1)
              LOAD_FAST                0 (n)
              LOAD_CONST               2 (1)
              BINARY_OP                0 (+)
              CALL                     2
              GET_ITER
      L1:     FOR_ITER                 7 (to L2)
              STORE_FAST               2 (i)

  7           LOAD_FAST_LOAD_FAST     18 (total, i)
              BINARY_OP               13 (+=)
              STORE_FAST               1 (total)
              JUMP_BACKWARD            9 (to L1)

  6   L2:     END_FOR
              POP_TOP

  8           LOAD_FAST                1 (total)
              RETURN_VALUE

The CPython VM is a stack machine: LOAD_* instructions push values onto a stack, BINARY_OP pops two and pushes the result, STORE_FAST pops one into a local variable. The instructions from L1: down to JUMP_BACKWARD are the loop. Each of those bytecode instructions costs the VM many machine instructions to carry out: decode the opcode, check the types of the operands, call the right C function, manage reference counts. This output is from Python 3.13.18 and is not trimmed. Bytecode is an implementation detail and changes between releases: 3.14 and 3.15 print different instruction names for the same function (LOAD_SMALL_INT, LOAD_FAST_BORROW, POP_ITER); the shape is the same.

The machine code GCC produced for the C version, shown as x86-64 assembly (the human-readable spelling of machine code):

gcc -O1 -S -masm=intel -fno-asynchronous-unwind-tables -fcf-protection=none sum_to.c
sum_to:
    test    edi, edi
    jle .L4
    add edi, 1
    mov eax, 1
    mov edx, 0
.L3:
    add edx, eax
    add eax, 1
    cmp eax, edi
    jne .L3
.L1:
    mov eax, edx
    ret
.L4:
    mov edx, 0
    jmp .L1

This is GCC 13.3 on Ubuntu; other GCC versions and other compilers produce different code. I trimmed the assembler directives (such as .file, .globl and .size) from sum_to.s and left every instruction and label as GCC wrote it. The two -f flags keep the file short: the first drops the .cfi directives used for stack unwinding, and the second drops the endbr64 instruction that Ubuntu’s GCC puts at the start of each function for control-flow protection.

On x86-64 Linux the first integer argument arrives in register rdi and the return value leaves in rax (edi and eax are their lower 32 bits, enough for an int); that agreement is the System V calling convention. A register is one of a handful of tiny, named storage slots inside the CPU itself, far faster than memory. Reading it with that in mind:

  • test edi, edi / jle .L4: if n is zero or negative, jump to .L4, which returns 0.
  • add edi, 1: turn n into n + 1, the value at which to stop.
  • mov eax, 1 / mov edx, 0: i lives in eax, total lives in edx.
  • .L3 is the loop: add i to total, add 1 to i, compare i with n + 1, and jump back to .L3 if they differ.
  • mov eax, edx / ret: move total into the return register and return.

The whole loop body is four instructions working entirely in registers. The compiler also reshaped your for loop into a do-while: one test before the loop, then the test at the bottom of each pass. Compile with -O0 (no optimization) instead and you get a version that loads and stores total and i from memory on every iteration, which is a good reminder that the machine code you get depends on how the compiler was asked to work, not only on what you wrote.

What the CPU does with it

The CPU runs one loop, forever, billions of times per second:

  1. Fetch the instruction at the address held in the program counter (on x86-64 the register is called rip, the instruction pointer).
  2. Decode it: which operation, which registers or memory addresses.
  3. Execute it: do the arithmetic, read or write memory, or load a new address into the program counter (that is all a jump is). Unless the instruction was a jump, the program counter moves on to the next instruction.

The CPU repeatedly fetches an instruction from memory at the program counter, decodes it, and executes it against registers and memory Every program on every machine, from your text editor to the Python VM, is this loop running over machine code.

Real processors overlap these steps for many instructions at once, guess which way branches will go, and reorder independent work, but the model above is the contract they present to software. Every if, loop and function call you write ends up as compares, conditional jumps and register moves.

How you write it changes how fast it runs

Two programs can compute the same answer and differ in speed by orders of magnitude. Usually the difference comes from where the work happens and how much of it is repeated, not from cleverness. Here are four demonstrations. Every number below came from at least three runs of each program on one 2-vCPU Intel Xeon cloud test machine (Python 3.13, Go 1.24), not on my own hardware. Run the code yourself; your ratios will differ, but the direction should not.

1. The same loop at top level and inside a function (CPython)

import time

N = 10_000_000

# The loop at module top level: total and i are global variables.
start = time.perf_counter()
total = 0
for i in range(N):
    total += i
top_level = time.perf_counter() - start


# The same loop inside a function: total and i are local variables.
def run():
    total = 0
    for i in range(N):
        total += i
    return total


start = time.perf_counter()
run()
in_function = time.perf_counter() - start

print(f"top level:   {top_level:.2f} s")
print(f"in function: {in_function:.2f} s")
print(f"ratio:       {top_level / in_function:.1f}x")

On the test machine the top-level loop took about 0.6 seconds and the function version about 0.3, roughly 2x across three runs. The code inside the loop is identical. The difference is the bytecode: at top level, total and i are globals, stored in a dictionary, so python3 -m dis shows LOAD_NAME and STORE_NAME, which look the name up in that dictionary every time. Inside a function they are locals, stored in a fixed array, so the bytecode is LOAD_FAST and STORE_FAST, which index straight into it. It is one reason Python scripts conventionally put their work in a main() function.

2. Moving repeated work out of the loop

def normalize_slow(values):
    result = []
    for v in values:
        result.append(v / max(values))   # max() rescans the whole list every pass
    return result

def normalize_fast(values):
    biggest = max(values)                # computed once, before the loop
    result = []
    for v in values:
        result.append(v / biggest)
    return result

With 5,000 values, the slow version took 210 to 245 ms and the fast one about 0.25 ms: a ratio between 700x and 1,000x across runs. The gap comes from growth, not from a constant factor. max walks the whole list, so the slow version does 5,000 walks of 5,000 items, 25 million steps, where the fast one does 10,000. Double the input and the slow version gets four times slower while the fast one gets twice as slow. Lifting work that does not change out of a loop is called hoisting, and optimizing compilers do it automatically when they can prove it is safe. CPython’s bytecode compiler does not attempt it, and could not prove it safe here anyway: as far as it knows, max might be rebound or return something different every time.

3. Rows versus columns (Go)

package main

import (
    "fmt"
    "time"
)

const n = 5000

var grid [n][n]int32 // one contiguous block: 5000 rows of 5000 four-byte integers

func sumByRows() int64 {
    var total int64
    for row := 0; row < n; row++ {
        for col := 0; col < n; col++ {
            total += int64(grid[row][col])
        }
    }
    return total
}

func sumByColumns() int64 {
    var total int64
    for col := 0; col < n; col++ {
        for row := 0; row < n; row++ {
            total += int64(grid[row][col])
        }
    }
    return total
}

func main() {
    for row := 0; row < n; row++ {
        for col := 0; col < n; col++ {
            grid[row][col] = int32(row + col)
        }
    }

    start := time.Now()
    a := sumByRows()
    byRows := time.Since(start)

    start = time.Now()
    b := sumByColumns()
    byColumns := time.Since(start)

    fmt.Println("same answer:", a == b)
    fmt.Println("by rows:   ", byRows)
    fmt.Println("by columns:", byColumns)
    fmt.Printf("ratio:      %.1fx\n", float64(byColumns)/float64(byRows))
}
same answer: true
by rows:    24.090477ms
by columns: 158.305434ms
ratio:      6.6x

Same additions, same answer, the two loops swapped, and the column version was between 5.5x and 7x slower across runs. The cause is the memory hierarchy. A Go array (like a C array) stores each row’s elements next to each other in memory. The CPU never fetches one integer from memory; it fetches a whole cache line (64 bytes on current x86-64 chips) and keeps it in a small, fast cache. Walking along a row uses all 16 integers in each line it fetches. Walking down a column jumps 20,000 bytes between reads, uses one integer per line, lands on a different 4 KB memory page every time, and by the time the loop comes back for the neighboring integer, that line has often been pushed out of the smallest, fastest cache. Nothing in the source code says “cache”, which is exactly why it catches people.

4. List versus set membership (CPython)

import time

N = 100_000
as_list = list(range(N))
as_set = set(as_list)
wanted = range(0, N, 100)        # 1,000 lookups spread across the data


def count_found(collection):
    found = 0
    for w in wanted:
        if w in collection:
            found += 1
    return found


start = time.perf_counter()
count_found(as_list)
list_time = time.perf_counter() - start

start = time.perf_counter()
count_found(as_set)
set_time = time.perf_counter() - start

print(f"list: {list_time * 1000:.1f} ms")
print(f"set:  {set_time * 1000:.3f} ms")
print(f"ratio: {list_time / set_time:.0f}x")

The list version took 250 to 320 ms and the set version about 0.07 ms, a ratio between 3,000x and 4,000x across runs. (A time that small is noisy, so treat the ratio as an order of magnitude, not a precise figure.) x in some_list checks items one at a time from the front, so its cost grows with the length of the list. x in some_set computes a number from x (its hash) and uses it to go almost directly to where it would be stored, so its cost stays roughly flat however big the set gets. The line if w in collection is identical in both cases. The data structure decided the speed.

The lesson across all four: the algorithm and the data layout you choose on the whiteboard matter far more than which language you translate into. Pick the right structure and the work you do not repeat, and then let the compiler worry about instructions.

Most languages are the same language

Underneath the syntax, mainstream languages share one small set of ideas: values, names, branches, repetition, functions and some way to group data. What differs is which of those ideas each language makes cheap to express and which it makes awkward. Here is one problem in six languages: count how many steps the Collatz rule (halve an even number, triple an odd one and add 1) takes to reach 1, starting from 27. Every version prints 111.

(defun collatz-steps (n)
  (cond ((= n 1) 0)
        ((evenp n) (1+ (collatz-steps (/ n 2))))
        (t (1+ (collatz-steps (+ (* 3 n) 1))))))

(format t "~d~%" (collatz-steps 27))
def collatz_steps(n):
    steps = 0
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        steps += 1
    return steps

print(collatz_steps(27))
#include <stdio.h>

int collatz_steps(long n) {
    int steps = 0;
    while (n != 1) {
        if (n % 2 == 0) {
            n = n / 2;
        } else {
            n = 3 * n + 1;
        }
        steps++;
    }
    return steps;
}

int main(void) {
    printf("%d\n", collatz_steps(27));
    return 0;
}
let rec collatz_steps n =
  match n with
  | 1 -> 0
  | n when n mod 2 = 0 -> 1 + collatz_steps (n / 2)
  | n -> 1 + collatz_steps (3 * n + 1)

let () = Printf.printf "%d\n" (collatz_steps 27)
package main

import "fmt"

func collatzSteps(n int) int {
    steps := 0
    for n != 1 {
        if n%2 == 0 {
            n = n / 2
        } else {
            n = 3*n + 1
        }
        steps++
    }
    return steps
}

func main() {
    fmt.Println(collatzSteps(27))
}
fn collatz_steps(mut n: u64) -> u32 {
    let mut steps = 0;
    while n != 1 {
        if n % 2 == 0 {
            n = n / 2;
        } else {
            n = 3 * n + 1;
        }
        steps += 1;
    }
    steps
}

fn main() {
    println!("{}", collatz_steps(27));
}

The skeleton is identical in all six: a stopping case (n is 1), a branch on even or odd, and either a counter in a loop or a “1 plus the rest” recursion. The Lisp and OCaml versions use recursion, the natural idiom in OCaml and a common one in Lisp (Common Lisp also has loop constructs), but the steps are the same steps. If you had the algorithm on a whiteboard, each version is a translation you could produce with a syntax reference open. I have written real code in all six, and the following is my opinion of what each makes easy and hard, not a ranking.

Lisp (here Common Lisp). Code is written as nested lists, the same structure the language uses for data, so programs can build and transform other programs. Macros use that to add new control structures to the language itself. Development happens in a live session where you redefine functions while the program runs. What is hard: the syntax is unfamiliar to almost everyone, the library ecosystem is small compared to the others here, and many type errors appear only when the code runs.

Python. The shortest path from an idea to a working script, with a large standard library and a package for nearly everything. It reads close to the steps on the whiteboard, which is why it teaches well. What is hard: CPU-bound code is slow, as the demos above show; type mistakes surface at run time unless you add type hints and a checker; and packaging and environments have a reputation for good reason.

C. Direct control over memory and data layout, tiny runtime, and a compiler for nearly every processor. Operating systems, language runtimes (including CPython) and most embedded code are written in it, so learning it shows you what the other languages are doing for you. What is hard: you manage memory by hand, the language has no built-in strings, lists or maps, and mistakes such as reading past the end of an array are undefined behavior, meaning the language makes no promise about what happens. Security bugs live there.

OCaml. Algebraic data types (a type that is “one of these shapes”, like Rust’s enum) plus exhaustive pattern matching make it excellent for anything tree-shaped: compilers, interpreters, parsers, symbolic math. Type inference gives you static checking without writing most types down. What is hard: the ecosystem is smaller, error messages take practice to read, and shared-memory parallelism only arrived with OCaml 5.0 in 2022.

Go. Small language, fast compiles, a single binary to deploy, a strong standard library for networking, and goroutines (lightweight threads managed by the Go runtime) for concurrency. It is very easy to read someone else’s Go, which matters more than people think. What is hard: error handling is explicit and repetitive (if err != nil everywhere), and the type system is deliberately plain; generics only arrived in Go 1.18.

Rust. Memory safety without a garbage collector (the runtime component that frees unused memory automatically in Python, Go, Java and OCaml), enforced at compile time by ownership rules and the borrow checker, plus enum and match borrowed from the ML tradition. When it compiles, a whole category of bugs is gone. What is hard: the learning curve is steep, the borrow checker rejects designs that would be fine in other languages until you learn to structure data its way, and compile times are long.

Why beginners get confused

Most beginner confusion has the same root: the person is discovering the algorithm while typing it, so they do not know what the program’s state should be at each step, and therefore cannot see where it went wrong. The specific symptoms are predictable. Each section above has its own; here are the ones that cut across everything.

= versus ==. = binds a name. == compares two values. In C, if (x = 5) assigns 5 and is always true; GCC warns with -Wall, and Python, Go and Rust refuse to compile it in an if. Cause: reading = as “equals” from math class.

Printing versus returning. print shows a value to a human. return hands it back to the caller. A function that prints and does not return gives the caller None:

def add(a, b):
    print(a + b)        # shows 5 to a human, hands nothing back

result = add(2, 3)
print(result)           # None

Cause: the screen shows the right number, so the beginner believes the function produced it. The whiteboard version of the step would have said “give back the sum”, not “show the sum”.

Off by one. range(3) is 0, 1, 2. A list of length 5 has indexes 0 to 4. Cause: never writing out the first and last values the loop will see. Trace the first iteration and the last iteration by hand and this class of bug disappears.

Copy versus reference. Covered under variables and functions: two names, one object. Cause: the “variable is a box” mental model.

The infinite loop. Cause: no step in the plan moves toward the stopping condition.

Reading error messages from the top. A Python traceback lists calls from the outermost to the innermost, and the line that matters is the last one, which names the exception and says what went wrong. Compilers are the opposite: fix the first error, because later ones are often consequences of it. Cause: nobody says this out loud.

Copying code you cannot explain. Code pasted from a search result or a chatbot answers a question you have not finished asking. It runs, then breaks in a way you cannot debug, because you never had the steps it implements. Cause: skipping the design step entirely.

Every one of these is a gap between what the programmer thinks the program does and what it does. You close that gap on paper first, by deciding what each variable holds after each step and checking it on a small example. Then the code has something to be checked against.

A worked example: from whiteboard to code

The problem: you have CPU readings for a server, one per minute, and you want the longest stretch of consecutive minutes above 90 percent. For [72, 95, 97, 60, 91, 93, 99, 96, 40] the answer is 4 (the run 91, 93, 99, 96).

Do not open an editor. Stand at the whiteboard and ask how you would do this by hand with a list on paper. You would run your finger along it, counting how long the current hot streak is and remembering the longest one you have seen. That is the algorithm. Write it as numbered steps in plain words:

1. Set current streak to 0. Set best streak to 0.
2. Look at each reading in order.
3. If the reading is above the limit:
   a. add 1 to the current streak.
   b. if the current streak is longer than the best, the best becomes the current.
4. Otherwise, the streak is broken: set the current streak to 0.
5. When there are no readings left, the answer is the best streak.

Now test the steps, still on the board, by tracing the example and writing down the state after each reading:

Reading Above 90? current best
72 no 0 0
95 yes 1 1
97 yes 2 2
60 no 0 2
91 yes 1 2
93 yes 2 2
99 yes 3 3
96 yes 4 4
40 no 0 4

The final best is 4, which matches. Then check the edges on the board too: an empty list never enters step 3 and returns 0; a list with no hot readings returns 0; a list that ends while still hot works because step 3b updates best as the streak grows, not when it ends. That last case is the bug most people write when they skip the trace: they only update best when the streak breaks, so a streak that runs to the end of the list never counts.

Only now open the editor. Each numbered step becomes a line or two, and the step numbers go in as comments so you can see the translation:

def longest_run_above(readings, limit):
    current = 0                      # step 1
    best = 0                         # step 1
    for reading in readings:         # step 2
        if reading > limit:          # step 3
            current += 1             # step 3a
            if current > best:       # step 3b
                best = current
        else:                        # step 4
            current = 0
    return best                      # step 5


cpu = [72, 95, 97, 60, 91, 93, 99, 96, 40]
print(longest_run_above(cpu, 90))       # 4
print(longest_run_above([], 90))        # 0
print(longest_run_above([10, 20], 90))  # 0
print(longest_run_above([95, 96], 90))  # 2

And the Go translation of the same steps, which needed no new thinking, only Go’s spelling:

func longestRunAbove(readings []int, limit int) int {
    current := 0                       // step 1
    best := 0                          // step 1
    for _, reading := range readings { // step 2
        if reading > limit { // step 3
            current++           // step 3a
            if current > best { // step 3b
                best = current
            }
        } else { // step 4
            current = 0
        }
    }
    return best // step 5
}

The translation needed no new decisions, because there was nothing left to figure out by the time the editor opened. The trace table told me what every variable had to hold at every step, so if the code had printed the wrong answer, you would know exactly where to look: compare the program’s state with the table, step by step. That is the whole method, and it scales: bigger problems get more steps and more boxes on the board, not a different process.

Sources and further reading