Notebooks
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
Notebook (.ipynb) | Script (.py) | |
|---|---|---|
| Runs | One cell at a time, in any order | Top to bottom, every time |
| Shows | Code, results, charts and text together | Only what you print or save |
| Best for | Exploring, teaching, sharing analysis | Production, schedules, tests |
| Version control | Harder to compare changes | Easy to compare and review |
Getting Started
| Command | Description |
|---|---|
pip install jupyterlab | It is used to install JupyterLab in your virtual environment |
jupyter lab | It is used to open JupyterLab in your browser |
Shift + Enter | It is used to run the current cell and move to the next |
| Kernel → Restart and Run All | It 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
- Explore in a notebook: load data, inspect, try charts, test ideas.
- Restart and run all to make sure the notebook works top to bottom.
- Move the code that works into a script or functions.
- 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:
- What does a notebook combine?
- Why restart and run all before trusting a result?
- When should code move from a notebook to a script?
Key Takeaways
Quick reference
| Need | Use |
|---|---|
| Explore data | Notebook |
| Share analysis | Notebook |
| Run every night | Script |
| Test and review | Script |
Was this tutorial helpful?