Scripts aren't notebooks
A script runs top to bottom in a fresh process every time. Unlearn the habits notebooks teach.
10 min
Sample page. Your Maestro, an AI, answers your free questions about this page.
If you learned Python in Jupyter, Colab or another notebook, you picked up habits that work there and break in a script. That's not your fault: notebooks are built for exploring, and scripts are built to be rerun.
| In a notebook | In a script |
|---|---|
| You run cells in any order you like | The file always runs top to bottom |
| Variables from earlier runs stay in memory | Every run starts fresh, with nothing in memory |
| A final expression in a cell displays its value | A bare expression does not display its value; use print() |
| "It worked" can depend on what you ran an hour ago | Each run follows the saved instructions, without leftover notebook variables |
Maestro's exercise box is an interactive environment too: it can display the final expression's value. The script column describes a .py file run from the terminal.
The second row matters most. In a notebook, you can create price in a cell, delete that cell, and keep using price until you restart the kernel. The notebook looks fine but can't be rerun from scratch. A script can't hide that: if a name isn't created above the line that uses it, the run stops with a NameError.
Why programs are scripts
Everything you'll go on to build (a scheduled report, a dashboard, a web API) is a script or a set of scripts. A server can't click cells in the right order; it starts your file and runs it from the top. Keeping all the instructions in the file makes rerunning them possible. Reproducing the same result also requires the same inputs and a compatible recorded environment; module 8 shows how to manage that environment.
Notebooks are still great for exploring data. The habit to build is knowing when work has to move into a script, and moving it so it runs top to bottom with nothing hidden.
Common mistake: The out-of-order cell
Running cell 5 before cell 3 works in a notebook if cell 3 ran earlier in the session. Paste those cells into a script in the order they appear on the page and it fails. In a script, the order on the page is the order it runs.
Try it
This script was copied from a notebook where the cells had run in a different order. Run it and read the last line of the error: it names the problem. Then reorder the lines so every name is created before it's used. A good result: the script runs with no error and prints 8.0.