Live code#
With live coding you can make your pages more interactive by adding live, executable code cells. This extension is already part of your TeachBooks book if you started from the template. If not, you can follow instructions in the manual to enable it. The template also includes a sample page with live code enabled, which you can find here for the website of the original template
With live code enabled, readers can run snippets directly in the browser, experiment with examples, and complete exercises in real time. This section will guide you through some of the main features available: additional cell tags have been developed that can be added to Python code cells in your book. These tags extend the existing Jupyter Book tags and allow you to control how cells behave when live execution is enabled.
Creating a notebook#
There are two ways you can try this exercise, depending on whether you have an IDE installed. If you don’t know what an IDE is, or don’t have one installed, follow Option 2 below.
In your repository, create a new notebook file in your book directory, e.g.
book/live_code_tags.ipynb
.To add a new code cell, use
python
and enter a simple code, for example:
```python
print("Hello world!")
```
With this setup, tags can be added by opening the cell metadata (in JupyterLab or Jupyter Notebook: View → Cell Toolbar → Tags
).
If you don’t have JupyterLab or VS Code installed, you can still add code in a markdown file. To make sure this is recognized as an interactive code cell, you need to add a Jupytext header. At the very top of your file (e.g.
book/live_code_tags.md
), add:
---
jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.17.3
kernelspec:
display_name: base
language: python
name: python3
---
Now you can insert executable code cells like this:
```{code-cell} ipython3
print("Hello world!")
```
With this setup, tags can be added directly into the code cell using :tags:
, for example:
```{code-cell} ipython3
:tags: ["hide-cell"]
print("Hello world!")
```