State and Execution Order
Unit ID: M01-U03 Estimated active time: 18-25 minutes
The notebook can look correct and still fail
Imagine a notebook with these cells in visual order.
Cell 1:
daily_budget = 1500
Cell 2:
remaining = daily_budget - spent
Cell 3:
spent = 925
If someone ran Cell 3 earlier, Cell 2 may work because the kernel remembers spent. But after a restart, running from the top fails at Cell 2. The notebook depended on hidden state: a remembered value created out of visible order.
Repair the order
Move the definition of spent before the calculation:
daily_budget = 1500
spent = 925
remaining = daily_budget - spent
print(remaining)
Output:
575
Now every value is created before it is used.
Why hidden state is risky
Hidden state can cause several problems:
- The notebook works for its author but fails for another learner.
- An old value remains after code has changed.
- Output on the page no longer matches the visible code.
- A later result depends on an experiment that was never documented.
These problems are especially serious in data and AI work. A clean-looking chart or summary is not reliable if nobody can reproduce the steps that created it.
A second hidden-state example
Run these lines in one cell:
rate = 10
hours = 4
payment = rate * hours
print(payment)
Output:
40
Now change rate to 12 but do not rerun the cell. The visible code says 12, while the kernel still remembers 10. If another cell prints payment, it still shows 40.
Code on the page and state in memory are not automatically the same. You must execute the changed code and any dependent calculations.
Use a clean-state test
The simplest test is:
- Save the notebook.
- Restart the kernel.
- Run all cells from top to bottom.
- Stop at the first error.
- Repair the missing or out-of-order step.
- Restart and run all again.
Do not merely run the failed cell repeatedly. Ask what it depends on.
Try this repair
The following code is out of order:
print(final_total)
tax = 18
subtotal = 200
final_total = subtotal + tax
Before running it, write the correct order. Then test your version.
One correct answer is:
subtotal = 200
tax = 18
final_total = subtotal + tax
print(final_total)
Explain the evidence
Complete this sentence in your own words:
The program failed after restart because ...
A strong answer names the missing dependency: a value was used before the cell that created it had run.
Takeaway
A notebook is reproducible when its visible order contains every required step. Restart-and-run-all exposes hidden state. Next, we will strengthen the habit that prevents many mistakes: read and predict before running.
