Imperative Programming
Imperative programming expresses computation as a sequence of commands that change program state.
2.1 Core idea
Imperative programming expresses computation as a sequence of commands that change program state. It is close to the operational view of a computer: execute an instruction, update memory, branch, and repeat.
Common features:
Variables and assignment Exceptions and early exits Mutable data structures Input/output operations
2.2 Variables and assignment
Output (CPython 3.13.1): Assignment changes which value a name refers to or updates a storage location, depending on language semantics. In imperative reasoning, it is useful to think in terms of program state before and after each statement.
temperature = 25
temperature = temperature + 1
print(temperature) # 262.3 Sequence and selection
A conditional chooses a path based on a Boolean expression. Check boundary conditions, including equality, empty input, and invalid values.
if (score >= 50) {
result = "Pass";
} else {
result = "Retry";
}2.4 Iteration
Loop correctness depends on:
Progress/update step Loop invariant, when reasoning formally
An infinite loop may be intentional for an event loop or embedded task, but it should still have defined exit, blocking, watchdog, and resource behavior.
let total = 0;
for (let i = 1; i <= 5; i++) {
total += i;
}2.5 Mutation and aliasing
Output (CPython 3.13.1): Both names refer to the same list object. This is aliasing. Mutations through one alias are visible through the other. Aliasing can be useful, but it complicates reasoning when shared mutable data crosses function or thread boundaries.
first = [1, 2]
second = first
second.append(3)
print(first) # [1, 2, 3][1, 2, 3]2.6 Exceptions and early exits
Exceptions can separate error handling from ordinary control flow. Use them for exceptional conditions according to the language and team conventions. Do not swallow errors silently or use exceptions as an uncontrolled substitute for ordinary branching.
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("b must not be zero")
return a / b2.7 Loop invariants
A loop invariant is a property that holds before the loop and remains true after each iteration.
For summing a list, after processing the first k items, total should equal the sum of those k items. Invariants help prove correctness and find off-by-one errors.
2.8 Strengths and trade-offs
Direct control over execution order Natural fit for stateful algorithms and hardware interaction Often easy to trace at a small scale
Mutation can make large systems harder to reason about Shared state complicates concurrency
Long procedures can hide responsibilities Tests may depend on setup and cleanup of state
Exercise
Implement a bounded counter with increment, decrement, reset, and overflow/underflow policy. Write tests for the minimum, maximum, and invalid operations.
Quiz
? `first = [1, 2]; second = first; second.append(3)` — what does `print(first)` show in Python?
- `[1, 2]` :: That would require `second` to be a copy.
+ `[1, 2, 3]` :: Both names refer to the same list object (aliasing); a real run printed this.
- An error :: Appending through an alias is legal.
- `[3]` :: `append` adds to the existing list.
? Which of these are needed to reason that a loop is correct? (select all that apply)
+ Initialisation :: The state before the first iteration.
+ A progress step that leads to termination :: Without progress the loop never ends.
+ A loop invariant :: A property that holds before and after every iteration.
- A global variable :: Globals are not required and often make reasoning harder.
? When is an intentional infinite loop acceptable?
+ In an event loop or embedded task, with defined exit, blocking, watchdog and resource behaviour. :: As the module says, intentional infinite loops still need defined behaviour.
- Never. :: Event loops and firmware main loops are legitimate infinite loops.
- Whenever the program is short. :: Program length does not make an unbounded loop safe.
- Only when it does not allocate memory. :: Memory is one concern;
…