PythonPython Environment and Development ToolsPython development tools

What is Jupyter Notebook?

Question 25 of 88 · Updated

On this page

Jupyter Notebook is an interactive, browser-based computing application that lets you combine executable code, explanatory text, mathematical notation, visualisations and saved results in a single notebook document. It is widely used for learning Python, exploring data, experimenting with machine learning and communicating computational findings.

Unlike a conventional Python script, which usually executes from beginning to end, a notebook can execute individual code cells and keep their results visible alongside the code. A separate computational process called a kernel executes those cells.

Jupyter is not a programming language and is not limited to Python. Python is a commonly used notebook language, but suitable kernels can support other languages such as Julia and R.

1. What does a Jupyter notebook contain?#

A notebook is organised into cells. Each cell has a particular role.

Cell typePurposeExample
CodeExecute code using the selected kernelCalculate a total, train a model or create a plot
MarkdownExplain the analysis using formatted textHeadings, tables, links and mathematical expressions
RawHold content that selected conversion tools may process without ordinary code execution or Markdown renderingExport-specific content

Code cells can produce several types of output, including printed text, expression results, images, tables, rich HTML and error messages. The available representations depend on the kernel, libraries, frontend and output-rendering capabilities.

For example, a data analyst can write an explanation of a calculation in a Markdown cell, perform the calculation in a code cell and display the result immediately below it. The notebook keeps the explanation and computation together.

2. How does Jupyter Notebook work?#

A typical local Jupyter session contains four important components:

Browser / notebook frontend
          |
          | user actions, cell source, displayed results
          v
Jupyter server
          |
          | kernel communication
          v
Python kernel (commonly IPython via ipykernel)
          |
          +--> Python interpreter and installed libraries
          +--> In-memory variables and objects

Notebook document (.ipynb)
    Stores cells, metadata and saved outputs

The frontend is where you edit cells, request execution and inspect outputs. The server manages notebook-related resources and communication. The kernel runs code in a computational process and returns results to the frontend.

In a typical Python notebook, ipykernel provides the Python kernel implementation using IPython facilities. It executes Python code and supports additional interactive features.

This separation means that the browser does not normally execute Python statements directly. It displays results from the selected kernel, which may run on your own computer or on a remote system.

The notebook document is separate from the running kernel. Saving a notebook does not automatically save every object in the kernel's memory.

3. What is an .ipynb file?#

The .ipynb extension identifies a Jupyter notebook document. The notebook format is structured JSON, containing cell sources, cell types, metadata and, for executed code cells, output records and execution counts.

A simplified conceptual structure is:

Notebook
    metadata
    format version
    cells
        Markdown cell
            source
        Code cell
            source
            execution count
            outputs

A saved notebook can therefore preserve both the instructions and previously produced results. Someone opening it may be able to read those results without executing the code again.

However, a notebook file does not normally contain all its external datasets, installed packages or live runtime state. Sharing only the notebook may not be sufficient to reproduce the analysis.

Notebook metadata can include the requested kernel's identity. That does not ensure that the matching kernel or dependency environment is installed on another computer.

4. How do you install and start Jupyter Notebook?#

Use an isolated Python environment, as discussed in the earlier Python environment lessons.

For Linux or macOS, an illustrative setup is:

BASH
python3 -m venv .venv source .venv/bin/activate python -m pip install notebook jupyter notebook

For Windows PowerShell, the corresponding setup can use the installed Python launcher:

POWERSHELL
py -3 -m venv .venv .\.venv\Scripts\Activate.ps1 python -m pip install notebook jupyter notebook

If an activation script is blocked, use the appropriate interpreter and executable paths directly rather than weakening security settings.

These commands require an available Python installation, compatible package artifacts and an approved package source. Jupyter was already installed in the local test environment; the installation and browser-launch commands were not independently exercised.

A successful local launch typically provides a URL for opening the notebook interface in a browser. Use the URL provided by the running server rather than assuming a fixed port or authentication method.

Keep a local notebook server accessible only to intended users. Do not expose it publicly without suitable authentication, transport security and access controls. A notebook kernel can execute arbitrary code with the permissions of the account running it.

When working in a managed Jupyter service, follow the service's environment, storage and security instructions instead of launching an unrelated server.

5. Practical example: an interactive sales notebook#

Create a Python notebook and add a Markdown cell describing the analysis:

MARKDOWN
## Sales summary Calculate the number of sales records, their total and their mean.

The heading and explanation appear as formatted documentation rather than executable Python.

Code cell 1: define the data#

PYTHON
sales = [120, 80, 100] len(sales)

Displayed expression result:

3

The list is stored in the running kernel's memory. In an ordinary IPython-backed notebook, the last expression can automatically produce a displayed result without an explicit print call.

Code cell 2: calculate the total#

PYTHON
total = sum(sales) print(f"Total: {total}")

Output:

Total: 300

The cell reuses the sales variable defined in the previous cell. It does not need to redefine the list because both cells execute in the same running kernel.

Code cell 3: calculate the mean#

PYTHON
from statistics import mean mean(sales)

Displayed expression result:

100

The statistics module is part of Python's standard library, so the numerical example does not require a third-party data-analysis package.

For n records, calculating a sum or mean requires O(n) arithmetic work under the usual fixed-cost arithmetic model. Actual costs can depend on the numeric types and implementation. The notebook interface does not remove the algorithm's computational cost.

These three code cells were executed in order in an actual Python Jupyter kernel during local testing, and their outputs were checked.

6. What is a notebook kernel, and why does execution order matter?#

A kernel is the computational process responsible for executing notebook code and maintaining runtime state.

Consider the sales example. If you execute the second cell before executing the first in a fresh kernel, the sales name has not been defined. It can raise NameError.

If you execute the first cell and then the second, the calculation succeeds because the kernel already holds the list.

Problems can also occur when a developer edits an earlier cell without rerunning dependent cells. Previously displayed outputs may represent the earlier input rather than the currently visible source.

Execution counts record the kernel's execution sequence for executed code cells. A notebook whose cells show execution counts out of sequence may have been run in a different order from the visible document order. Counts alone cannot guarantee reproducibility, especially when kernels have been restarted or outputs edited.

To check an analysis before sharing it:

  1. Save the current source.
  2. Restart the kernel to clear its current in-memory state.
  3. Run all cells from top to bottom.
  4. Check errors, outputs and external dependencies.
  5. Save the verified notebook.

Exact menu labels differ between notebook frontends and versions.

A kernel restart does not automatically undo files, database writes or other external effects produced by earlier execution. Design such operations carefully and make repeated execution safe where possible.

Local testing confirmed that a fresh kernel did not inherit the sales variable from the previous kernel.

7. How do you identify the Python environment used by a notebook?#

A common beginner issue occurs when a package is installed into one Python environment but the notebook uses another.

Run this diagnostic inside a code cell:

PYTHON
import sys print(sys.executable) print(sys.version)

The executable path and version depend on the machine and selected kernel. The locally tested kernel used Python 3.13.5.

If an import fails, compare the notebook's sys.executable with the interpreter used to install the package. The terminal running the notebook server can belong to a different environment from the computational kernel.

A project can register an IPython kernel for a specific environment. For example, after installing ipykernel into the desired environment, a commonly used command is:

BASH
python -m ipykernel install --user --name project-demo --display-name "Python (project-demo)"

Run the command using the intended project interpreter. Select the registered kernel in the notebook frontend.

Registration creates a kernel specification that points to an environment; it does not duplicate the environment or install all of its dependencies. If that environment is later removed, the registered kernel may become unusable.

The registration command is an illustrative setup instruction and was not run in the local tests.

8. What are IPython magic commands?#

IPython-backed notebooks provide special commands known as magics. They are additional interactive syntax supported by IPython, rather than ordinary Python syntax.

For example:

PYTHON
%pwd

This line magic displays the current working directory. The output is environment-specific. It was executed successfully in the local notebook test.

Line magics usually begin with a single percent sign, and cell magics use two percent signs when supported.

Another useful example is the IPython-specific %pip magic, which is designed to run pip within the current kernel's environment. Before installing any package, verify the intended dependency, version and trusted source. A kernel restart may be needed after certain changes.

Do not place IPython-specific magic syntax directly into an ordinary .py file and expect the standard Python parser to accept it. The notebook's interactive capabilities are additional to the Python language.

9. How does Jupyter display rich output?#

A Python kernel can send output representations to the frontend instead of returning only plain terminal text.

For example:

PYTHON
from IPython.display import Markdown, display display(Markdown("**Analysis complete**"))

The notebook can display the phrase Analysis complete using formatted Markdown. During local testing the actual kernel returned a text/markdown representation containing that phrase.

Libraries can also provide representations for figures, tables and other objects. A plotting library may produce a rendered image, while a data-analysis library may produce a formatted table.

The kernel and frontend cooperate to display the result. The browser rendering and visual style may vary. Some output types require additional frontend support.

10. Jupyter Notebook vs a Python script#

FeatureJupyter notebookPython script
Typical file extension.ipynb.py
Execution styleIndividual cells or a sequence of cellsUsually top-to-bottom execution
Runtime stateShared across cells in a running kernelNormally begins with a new process when invoked
DocumentationMarkdown cells and rich explanationsComments, docstrings and external documentation
OutputsCan be stored with the documentUsually printed, logged or written elsewhere
Typical useExploration, demonstrations, analysis and teachingReusable programs, services, automation and library code

A notebook is often an excellent starting point for experimentation. A script or reusable module is frequently more suitable when a workflow needs reliable command-line execution, unit testing, deployment or integration with other software.

These approaches are complementary. For example, put reusable data-cleaning logic in a Python module, test it separately, then import it into a notebook to explore the results.

Jupyter Notebook and JupyterLab are also related but distinct interfaces in the Jupyter ecosystem. Both can work with notebooks; JupyterLab provides a broader workspace-oriented interface. The detailed comparison belongs to the next lesson.

11. How do you share a reproducible notebook?#

A notebook intended for another developer should contain clear instructions and a complete description of its computational requirements.

Include:

  • The required Python version and dependency specification.
  • Instructions for obtaining permitted input datasets.
  • An explanation of expected execution order and outputs.
  • Relevant configuration requirements without credentials.
  • The assumptions and limitations of the analysis.

Notebook files can contain substantial saved output, including data, charts, HTML and error messages. Inspect both cell source and output before sharing. Removing a sensitive variable from a code cell does not necessarily remove a previously saved output containing its value.

Where an analysis uses randomness, set appropriate random seeds where applicable, while recognising that seeds alone may not guarantee identical results across different libraries, hardware and versions.

For important workflows, automate notebook execution in a clean environment. Tools such as nbclient can execute notebooks through a kernel, allowing teams to detect failures without manually running every cell.

A notebook can be exported to formats such as HTML or, using appropriate conversion tools and dependencies, other formats. An exported report is not necessarily an executable notebook.

12. Practical engineering example: verify a notebook programmatically#

The following example constructs and runs a minimal notebook using nbformat and nbclient. It requires those packages and an available Python kernel.

PYTHON
from nbformat.v4 import new_notebook, new_code_cell from nbclient import NotebookClient notebook = new_notebook( cells=[ new_code_cell("sales = [120, 80, 100]"), new_code_cell("sum(sales)"), ] ) NotebookClient( notebook, kernel_name="python3", timeout=20, ).execute() print(notebook.cells[1].outputs[0].data["text/plain"])

Expected output:

300

This pattern executes a real computational kernel and inspects the captured expression result. It is useful for validating notebooks in automated workflows, but it does not by itself prove that every conclusion in an analysis is correct.

Only execute notebooks you trust. Automated execution of arbitrary uploaded notebooks is a code-execution capability and requires a properly designed security boundary.

13. Common mistakes and troubleshooting#

The notebook works only when cells are run in a certain hidden order#

Restart the kernel and run all cells. Make dependencies explicit and keep the visible order understandable.

A package is installed but cannot be imported#

Inspect sys.executable inside the notebook. Verify that the selected kernel belongs to the environment where the distribution was installed.

A notebook shows an old chart or result#

Saved outputs can remain visible after source edits. Rerun the affected cells and verify dependent results before relying on them.

Closing the browser is assumed to stop all computation#

A server and kernel can continue running independently of a browser tab. Shut down unused kernels or sessions through the available interface or managed service to release resources.

A notebook includes passwords or personal data#

Never store secrets in cell source, notebook metadata or saved outputs. Inspect the complete notebook before committing it to version control or sharing it. Rotate credentials if they have been exposed.

A notebook from an unknown source is executed immediately#

Review its source and dependencies first. Notebook trust mechanisms can restrict rendering of certain untrusted saved outputs, but they are not a sandbox for executing arbitrary code.

14. Frequently asked questions#

Is Jupyter Notebook an IDE?#

It is an interactive notebook application with development capabilities. It differs from a traditional general-purpose IDE because its central workflow is document-based, cell-oriented computation.

Is Jupyter Notebook part of Python's standard library?#

No. Jupyter is a separate software ecosystem that must be installed or provided by an environment or hosted service.

Can Jupyter Notebook run languages other than Python?#

Yes. Jupyter supports different computational kernels. A suitable installed kernel is required for the chosen language.

Does saving a notebook save every variable in memory?#

No. The notebook document stores sources, metadata and saved outputs. Kernel memory and external resources are separate.

Can I use Jupyter Notebook without internet access?#

Yes, a properly installed local notebook environment can execute code offline when its dependencies and required data are available locally.

Interview-ready answer#

Jupyter Notebook is an interactive, browser-based application for creating computational documents that combine executable code cells, Markdown explanations, visualisations and saved outputs. A computational kernel, commonly IPython through ipykernel for Python, executes the cells and maintains their shared runtime state. Notebooks are stored as .ipynb files. They are useful for data exploration, machine-learning experimentation, education and reproducible reporting. Because cells can be executed out of order, developers should restart the kernel and run all cells to verify a notebook before sharing it. Reusable application logic is often better maintained in tested Python modules alongside notebooks.

Key takeaways#

  • Jupyter Notebook combines code, explanations and results in one document.
  • A kernel executes code and maintains in-memory state across cells.
  • The .ipynb format stores notebook contents but not the complete runtime environment.
  • Use explicit kernel selection and clean execution to improve reproducibility.
  • Treat notebooks as executable code and inspect both source and saved outputs before sharing.

Official references#

Verification note: Local tests used Python 3.13.5, Notebook 7.5.3, IPython 9.14.0, ipykernel 7.2.0, nbformat 5.10.4 and nbclient 0.10.4. A valid notebook was written, read and executed in a real Python kernel; expression results, printed output, Markdown MIME output, the working-directory magic and fresh-kernel isolation were checked. Browser rendering, new package installation, kernel registration and live references were not independently verified under the authorised offline research exception.

References

  1. 1.
    Jupyter Notebook documentationjupyter-notebook.readthedocs.io
  2. 2.
  3. 3.
  4. 4.
    Jupyter nbclient documentationnbclient.readthedocs.io
  5. 5.
  6. 6.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design