6 Python Code in Quarto Document
6.1 Use of Python Code in Quarto Document
To use Python code in a Quarto document, you can embed Python code chunks in your .qmd file. Quarto supports several programming languages, including Python, and allows you to execute code in the document, similar to how Jupyter Notebooks work.
Here’s how to include and run Python code in a Quarto document.
6.2 Steps To Follow
- Install Required Tools
Make sure you have Python installed.
Install Jupyter if you haven’t already, as Quarto uses Jupyter to execute Python code.
You can install Jupyter using the following command:
pip install jupyter
- Set up Quarto
- Install Quarto if you haven’t done so. You can download and install it from quarto.org
- Write Python Code in Quarto Document
In your Quarto document (.qmd), you can include Python code chunks by specifying {python} at the start of the chunk.
---
title: "Python in Quarto"
format:
html: default
pdf: default
---
# Python Example in Quarto
Here’s a simple Python example embedded in a Quarto document.
# Python code
import numpy as np
# Generate random numbers
random_numbers = np.random.rand(5)
random_numbers
### 4. Render the Quarto Document
You can render the Quarto document using:
- In the terminal:
quarto render your_document.qmd
- In Visual Studio Code or RStudio: Use the Render button if you are working with these editors. The output will include both the code and its result in the specified format (HTML, PDF, etc.).
- Output Formats
Quarto supports various output formats (e.g., HTML, PDF, MS Word). Specify the format in the YAML header at the top of your .qmd file:
---
title: "Python Example in Quarto"
format:
html: default
pdf: default
---
Example of a Full Quarto Document with Python Code
---
title: "Python in Quarto Example"
format: html
---
# Using Python in Quarto
You can run Python code directly within Quarto documents.
# Import the necessary library
import numpy as np
# Generate 10 random numbers
random_numbers = np.random.rand(10)
random_numbers
The output of the Python code will be rendered inline in your document.
### 6. Additional Tips
- **Code Chunk Options**: You can control the output behavior of Python code chunks using options like `echo`, `eval`, `include`, and `results`.
- `echo`: Whether to show the code in the output (`true` or `false`).
- `eval`: Whether to evaluate the code chunk (`true` or `false`).
- `results`: How to display the results (`"asis"` for raw output, `"hide"` to hide results).
Example:
print("This is a Python print statement")
ssh-keygen -t ed25519 -C “analystnyamu79@gmail.com”