Run Code Cells in Notebooks

Learn to run code cells and markdown in Jupyter notebooks with this hands-on Python tutorial. Discover the core concepts, step-by-step execution, and troubleshooting tips to boost your data science workflow.

Focus: run code cells and markdown in notebooks

Sponsored

You've just imported a messy CSV, cleaned it with pandas, and plotted a trend line — but when you close the notebook and come back the next morning, the outputs are gone and you have no idea which cell produced that killer chart. Worse, your collaborator runs your notebook top-to-bottom and gets a different result because you executed cells out of order. This is the daily reality of data scientists who never learned to control how code cells and markdown cells behave in Jupyter notebooks. In this lesson, you'll master the mechanics of running cells — from keyboard shortcuts to execution state — so your notebooks become reproducible, readable, and reliable instruments of analysis.

The problem this lesson solves

Jupyter notebooks are the de facto standard for exploratory data analysis, but their flexibility is a double-edged sword. You can run cells in any order, edit them after execution, and mix prose with code. That freedom, without discipline, leads to three classic problems:

  • Hidden state: Variables linger in memory even after you delete the cell that created them. A cell that ran fine at 2 PM fails at 5 PM because an earlier df.head() overwrote a variable you forgot about.
  • Non-reproducible results: Your script works on your machine, but your colleague runs it and gets a KeyError because you manually skipped a cell that defined a needed column.
  • Readability chaos: A notebook with 30 code cells and zero markdown might as well be a .py file with no comments — impossible to follow for anyone (including future you).

If you don't actively manage how you run cells and how you document your process, your analysis becomes untrustworthy. This lesson gives you the tools to turn a notebook from a sketchpad into a clean, reproducible report.

The solution isn't to abandon notebooks — it's to master them. By the end, you'll know exactly how to execute cells, when to use markdown, and how to avoid the pitfalls that trip up even experienced Python developers.

Core concept / mental model

Think of a notebook as a conversation between you and Python. Each code cell is a question you ask; the output is the answer. Markdown cells are your notes in the margin — explanations, hypotheses, and conclusions that give context to the code. Unlike a traditional script, this conversation is stateful: every cell shares the same memory. It's like a whiteboard where each marker stroke builds on the last.

Key terms you need to know:

  • Kernel: The Python interpreter that executes code. When you run a cell, the kernel processes it and returns the result. The kernel holds all variables, imported modules, and functions.
  • Code cell: A block of executable Python code. You run it with Shift+Enter (or Ctrl+Enter to stay on the same cell).
  • Markdown cell: A block of formatted text (headings, bullets, code snippets in backticks, even LaTeX math). Double-click to edit, Shift+Enter to render.
  • Execution order: The number in square brackets to the left of each cell, e.g., [3]. This is your map — it tells you (and others) the exact sequence of execution.

The mental model: Notebooks are not files you run; they are environments you interact with. Each cell execution is a command to the live kernel, and the output (printed text, plots, DataFrames) is the kernel's response. Markdown cells don't execute — they render. Their job is to make the conversation comprehensible.

How it works step by step

Here's the standard workflow for executing code in a Jupyter notebook:

  1. Write code in a code cell. Start typing Python. Use Tab for autocompletion, Shift+Tab for docstrings.
  2. Run the cell. Press Shift+Enter (runs and moves to next cell) or Ctrl+Enter (runs and stays). Alternatively, click the Run button in the toolbar. The cell's border turns solid, and Python processes it in the background.
  3. See the output. Printed text appears directly below the cell. If the last line is an expression (like df.head()), the notebook displays a rich representation — often a styled table.
  4. Check the execution counter. The [n] increments each time a cell runs. If you run a cell twice, it gets a new number, which can signal trouble (more in Troubleshooting).
  5. Interrupt or restart if stuck. Use the Stop button (or I I) to halt a long-running cell. Use Kernel → Restart to clear all variables and start fresh.

Markdown cells follow a parallel path:

  • Double-click a markdown cell to enter edit mode. The text becomes plain source (with # for headings, * for emphasis, and backticks for code).
  • Press Shift+Enter to render it as formatted output. You'll see headings, bold text, and list markers appear.
  • To edit again, double-click the rendered content. Markdown is pure text, so it's version-control friendly.

The key insight: Execution order matters more than cell order. You can arrange cells visually in any linear sequence, but the kernel only knows the order in which you ran them. Always run cells in a logical top-to-bottom order to keep the state consistent with what a reader sees.

Hands-on walkthrough

Let's put this into practice with a real notebook session. We'll create a simple analysis of a sample dataset to see how code and markdown work together.

Example 1: A minimal notebook session

Open a new Jupyter notebook and enter the following in a code cell:

import pandas as pd
df = pd.DataFrame({'name': ['Ada', 'Grace', 'Alan'], 'age': [36, 45, 41]})
print(df.head())

Press Shift+Enter. You should see:

   name  age
0   Ada   36
1  Grace  45
2  Alan   41

The cell executed, and the output is printed below. The kernel now stores df for later cells.

Example 2: Using markdown to explain

Insert a new cell above the code cell and make it markdown (use the dropdown menu or press M when the cell is selected). Type:

# Employee dataset
This DataFrame lists three pioneers of computing and their ages at a certain time.

Press Shift+Enter. Now your notebook has a heading and a paragraph that make the code meaningful. Anyone reading it knows why this data exists.

Example 3: Running cells in a specific order

Create a second code cell below the first:

print(df['age'].mean())

Run it: you'll get 40.666666666666664. Now go back to the first code cell and run it again with Ctrl+Enter. Notice the execution counter changes to [2]. The output is the same, but the counter now shows [2]. If you run the mean cell again, it becomes [3]. This is normal, but if you see non-sequential numbers while reading, it's a sign the notebook was executed out of order.

Example 4: Using keyboard shortcuts for speed

Here's a cheat sheet for faster cell management:

Shortcut Action
Shift+Enter Run cell, move to next
Ctrl+Enter Run cell, stay put
Alt+Enter Run cell, insert new cell below
M Convert cell to markdown
Y Convert cell to code
A / B Insert cell above / below
D D Delete selected cell

Try Alt+Enter after a code cell to quickly add a markdown note, then type and render it. With practice, you'll navigate notebooks without touching the mouse.

Compare options / when to choose what

When working with notebooks, you have choices about how to run code and when to use markdown vs. code. Let's compare the main execution modes and documentation approaches.

Execution modes

Mode When to use Pros Cons
Shift+Enter Default for linear execution strategies Moves you forward naturally Can accidentally skip cells if you're not paying attention
Ctrl+Enter Re-running a cell after editing Stays in context for fine-tuning Doesn't advance, easy to get stuck on one cell
Run All (Kernel → Restart & Run All) Reproducible final report Clears all state and runs top-to-bottom Can be slow; may fail if a cell depends on manual input
Run All Below When you've edited earlier cells Saves recomputing the top Still relies on current kernel state

Markdown vs. code for documentation

Approach Best for Example
Markdown cell Describing intent, methodology, results "We filtered to East Coast stores because..."
Code comment (#) Short, inline notes within a complex expression # drop duplicates before merge
Print statements Debugging and runtime logs print('shape:', df.shape)

Use markdown for narrative and comments for micro-explanations. Both are essential for a professional notebook.

Troubleshooting & edge cases

Even experienced users hit wall. Here are common issues and how to fix them:

1. Stale output after editing a cell

Symptom: You fix a bug in a cell, run it, but the displayed result is still the old one. Cause: You forgot to run the cell (or ran a different one). Output only updates when you execute the cell. Fix: Press Ctrl+Enter to run exactly that cell. Check the execution counter to confirm it changed.

2. Variable not defined despite running earlier cell

Symptom: NameError: name 'x' is not defined, even though you saw the variable created. Cause: The kernel was restarted (all state cleared) or the defining cell never ran in the current session. Fix: Run the cell that defines the variable again, or use Kernel → Restart & Run All to reproduce the entire notebook.

3. Out-of-order execution causing weird results

Symptom: Your notebook produces different numbers every time you run it, or a cell works when run alone but fails in sequence. Cause: You executed cells in a non-top-to-bottom order, so the state doesn't match the visual arrangement. Fix: Use Kernel → Restart & Run All to guarantee a clean run. Always try this before sharing a notebook.

4. Markdown shows raw text instead of formatting

Symptom: You see ## Heading text instead of a big heading. Cause: The cell is still in edit mode, or it's actually a code cell. Fix: Press Shift+Enter to render. If it's still plain, check the cell type (should be Markdown in the toolbar) and convert with M.

5. Long-running cell never finishes

Symptom: The kernel is busy (circle icon) and you can't run anything else. Cause: Infinite loop or heavy computation. Fix: Click the Stop button or press I I to interrupt. If it still hangs, use Kernel → Restart to kill everything.

Pro tip: Before running a cell that might take a while, add a quick print at the end to confirm completion. It's like a breadcrumb in the logs.

What you learned & what's next

You now understand how to run code cells and markdown in notebooks, the mental model of a stateful kernel, and the practical shortcuts to move quickly. You can diagnose common execution problems, and you know how to use markdown to transform a raw script into a readable story. You've also seen that execution order is a core pillar of reproducibility — a skill that will save you hours and earn trust from collaborators.

The next lesson in this track builds on this foundation by diving into sharing and exporting notebooks. You'll learn how to convert your polished notebook into a standalone report or a deployed dashboard, keeping the analysis intact while making it accessible to stakeholders who never touch code.

Before you go, remember the three pillars: run, document, reproduce. Master them, and your notebooks will be as professional as your Python.

Practice recap

Open a notebook, write a code cell that creates a DataFrame and prints its summary, then add a markdown cell above it explaining what the data represents. Run the cells in order, then re-run the code cell after editing it, and observe the execution counter. Finally, restart the kernel and run all cells from the top to see the notebook reproduce cleanly.

Common mistakes

  • Running cells out of order and then sharing the notebook without a 'Restart & Run All' check — leads to confusing, non-reproducible results.
  • Using code comments for everything instead of markdown cells, making the notebook cluttered and harder to read.
  • Forgetting to re-run a cell after editing it, so the output shown is stale and doesn't match the current code.
  • Assuming the kernel retains state after a restart — variables are lost, so careful rerun of all needed cells is required.

Variations

  1. Use JupyterLab instead of the classic notebook interface — it offers split views and a more powerful file browser.
  2. Run cells in VS Code with the Jupyter extension, which provides IntelliSense and variable explorer in a familiar IDE.
  3. Use nbconvert to execute a notebook from the command line, which is useful for automated pipelines that need to run notebooks end-to-end.

Real-world use cases

  • A data scientist explores a new dataset, running cells incrementally to test transformations and visualizations, documenting each step with markdown.
  • A research team shares an analysis notebook where each section combines markdown explanations and code cells, allowing reviewers to read the narrative and re-run the code.
  • A data engineer triggers a nightly Python script that uses nbconvert to execute a notebook and exports the results to an HTML report for stakeholders.

Key takeaways

  • Notebooks are stateful: every code cell shares the same kernel, so execution order matters more than cell order.
  • Use Shift+Enter and Ctrl+Enter to control whether you advance or stay, making code execution fast and deliberate.
  • Markdown cells turn your notebook into a narrative — use headings, bullets, and code snippets to guide the reader.
  • Always test your notebook with 'Restart & Run All' before sharing to ensure results are reproducible from a clean state.
  • Troubleshooting common issues like stale outputs and missing variables starts by checking whether the cell actually ran and the kernel state.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.