Notebooks

Updated · 4 min read
easyPython 3.13aipythonjupyternotebooksscripts

A Jupyter notebook is a document that mixes text, runnable code cells and their results, including tables and charts, in one place. It is used for exploring data, trying ideas step by step and sharing analysis with others. A script is a plain .py file that runs from top to bottom, and it is used for code that must run the same way every time.

Notebook vs Script

Explore in a notebook; run reliably in a script
Notebook (.ipynb)Script (.py)
RunsOne cell at a time, in any orderTop to bottom, every time
ShowsCode, results, charts and text togetherOnly what you print or save
Best forExploring, teaching, sharing analysisProduction, schedules, tests
Version controlHarder to compare changesEasy to compare and review

Getting Started

CommandDescription
pip install jupyterlabIt is used to install JupyterLab in your virtual environment
jupyter labIt is used to open JupyterLab in your browser
Shift + EnterIt is used to run the current cell and move to the next
Kernel → Restart and Run AllIt is used to rerun every cell from the top, in order

Many code editors, such as Visual Studio Code, can also open and run notebooks directly.

The Usual Path

  1. Explore in a notebook: load data, inspect, try charts, test ideas.
  2. Restart and run all to make sure the notebook works top to bottom.
  3. Move the code that works into a script or functions.
  4. Run the script in production, on a schedule, or in tests.

Common Mistakes

Running cells out of order. Results can depend on a cell you ran earlier and later deleted.

Shipping a notebook to production. Move working code into a script with tests.

Sharing notebooks with secrets or private data in outputs. Clear outputs and check before sharing.

Interview Corner

When would you use a notebook instead of a script?

For exploring data, prototyping and sharing analysis, where seeing results step by step helps. Use scripts for code that must run reliably, such as production jobs and tests.

What is the main risk of notebooks?

Hidden state from running cells out of order, so results may not be reproducible. Restarting and running all cells from the top checks this.

Practice

Exercise: notebook to script. In a notebook, load payments.csv, clean it and chart payments by month, one step per cell. Restart and run all. Then move the working code into payments_report.py and run it from the terminal.

Check your understanding:

  1. What does a notebook combine?
  2. Why restart and run all before trusting a result?
  3. When should code move from a notebook to a script?

Quick check: notebooks

4 questions
1What is a Jupyter notebook?
2What does "Restart and Run All" check?
3Which is best for a nightly production job?
4Where should an API key go?

Key Takeaways

Quick reference

NeedUse
Explore dataNotebook
Share analysisNotebook
Run every nightScript
Test and reviewScript

Was this tutorial helpful?

Lesson 81 of 186