Executed python - Example

Example of a web page with executed python code
Author

Ludovic Deneuville

1 Python

If you want to run python code in your quarto document, first you will have to :

    • pip install jupyter
    • pip install matplotlib numpy pandas ...
Tip

Instead of install packages one by one

  • list all needed packages in file requirements.txt at the project root
  • run pip install -r requirements.txt

Official documentation :

2 Cells

2.1 How it works ?

On the left side, you can see the code entered in the .qmd file, and on the right side, you can see the result.

Code in your .qmd file

```{python}
a = 1
print(a + 1)
```

Output (Code + result)

a = 1
print(a + 1)
2

2.2 Cell options

Cell options impact the execution and output of executable code blocks.
They are specified within comments at the beginning of a block.

Some option examples :

```{python}
#| label: my_label         # Unique label for code cell
#| eval: true              # Evaluate the cell
#| echo: true              # Print the code
#| output: false           # Don't print the output
#| warning: false          # Hide warnings
b = [1, 2, 3, 4]
print(b)
```

2.3 Imports

To facilitate import management, it is recommended to group all of them in the first cell.

import numpy as np
import matplotlib.pyplot as plt

from scipy.stats import norm
from IPython.display import Markdown
from tabulate import tabulate

2.4 A non-evaluated cell

If you add a dot (.) before the keyword python, the cell will not be evaluated.

Code

```{.python}
x = np.linspace(-5, 5, 1000)

pdf = norm.pdf(x, 0, 1)
plt.plot(x, pdf, label='Normal Distribution')
plt.show()

Output

x = np.linspace(-3, 3, 1000)

pdf = norm.pdf(x, 0, 1)
plt.plot(x, pdf, label='Normal Distribution')
plt.show()

2.5 An evaluated cell

if you remove the dot (.) before the keyword Python, the cell will be evaluated.

x = np.linspace(-3, 3, 1000)

pdf = norm.pdf(x, 0, 1)
plt.plot(x, pdf, label='Normal Distribution', color='darkcyan')
plt.show()

3 Tabulations

4 Line numbers

def fibonacci(n) -> list[int]:
    """Generate the Fibonacci sequence up to the nth term."""
    if not isinstance(n, int):
        raise TypeError("n must be an integer")

    fib_sequence = []
    a, b = 0, 1
    for _ in range(n):
        fib_sequence.append(a)
        a, b = b, a + b
    return fib_sequence

# Example usage
fib_10 = fibonacci(10)
mean_fib_10 = np.mean(fib_10)

print(fib_10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

5 Inline code

It is possible to embed code within a line of text :

  • The mean of fibonacci(10) is np.float64(8.8).