Computations

Introduction

This guide provides an overview of how to integrate Python with Quarto. Suitable for beginners and experienced users alike, this resource provides straightforward instructions on setting up Python and Jupyter to work with Quarto, allowing you to execute Python code blocks within your documents. Here’s what you’ll learn:

  • Installation and Setup: Instructions on installing Python and Jupyter, and verifying your setup with Quarto.
  • Executing Python Code: Details on how to insert and run Python code blocks, and how to handle inline code for real-time updates in your documents.
  • Practical Examples and Tips: Includes examples that show you how to use Python in Quarto documents, along with tips on rendering and integrating code effectively.
  • Advanced Features: Dive into advanced functionalities like using inline expressions and adding markdown within code outputs through IPython.


Prerequisites

Install Python 3 and the jupyter package.

Install using one of the following methods:

  1. Using Pip:
    • Mac/Linux: python3 -m pip install jupyter
    • Windows: py -m pip install jupyter
  2. Using Conda: conda install jupyter

Verify that Quarto is configured correctly for Jupyter with:

Terminal
quarto check jupyter

Code Block

Executable Python code blocks ```{python}. Example:

---
title: "Python Code"
jupyter: python3
---

Example of code: 

```{python}
print("Hellow World")
```

Inline Code

  • Embed live code in markdown with a single tick (`) instead of triple (```).
  • Example: Set radius in a code block and reference it in text with inline code.
```{python}
radius <- 5
```

The radius of the circle is `{python} radius`
Important
  • Inline expressions in .qmd files auto-evaluate when rendered or previewed.
  • For notebook inline expressions, you should execute: quarto render notebook.ipynb --execute. Alternatively, you can enable execution within the notebook’s YAML part (see below).
---
title: "My Notebooks"
execute:
  enabled: true
---

Use IPython.display.Markdown to include markdown syntax in inline expressions:

```{python}
radius = 10
from IPython.display import Markdown
```

The radius of the circle is `{python} Markdown(f"_radius_ = **{radius}**.")`

Rendering

Read rendering Quarto documents containing Python or R code blocks.

References