Tmx
Tmx

Reputation: 597

How to have python code and markdown in one cell

Can jupyter notebook support inline python code (arthritic calculations, or plot a figure) in markdown cell, or verse visa. Have both python code and markdown in one cell.

Upvotes: 16

Views: 19833

Answers (4)

Rub
Rub

Reputation: 2748

If you accept Colab as 'jupyter notebook' , then the answer is YES.

Here some examples.

  • Upper part, code cell
  • Lower part, markdown cell

enter image description here

Code in the code cell:

#@markdown  # Title

#@markdown   **black**

#@markdown  `code stuff`

#@markdown ![Image in a code cell]( https://i.imgur.com/6Z1i8zF.png)

Very useful for when you want to insert an image within a code cell.

Upvotes: 2

Narek
Narek

Reputation: 616

You can use the magic function below

%%md_with_code
"""
# Title

More markdown
"""

my_code.execute()

Here is the code for the magic function

from IPython.display import display, Markdown
from IPython.core.magic import register_cell_magic
from IPython import get_ipython
import ast

@register_cell_magic
def md_with_code(line, cell):
    parsed = ast.parse(cell)
    if not parsed:
        return
    
    if isinstance(parsed.body[0], ast.Expr) and isinstance(parsed.body[0].value, ast.Str):
        display(Markdown(parsed.body[0].value.s.strip()))
    get_ipython().run_cell(cell)

del md_with_code


del md_with_code

Upvotes: 0

Kevin Zhu
Kevin Zhu

Reputation: 2846

from IPython.display import display, Markdown
display(Markdown("# Hello World!"))

Upvotes: 25

MSeifert
MSeifert

Reputation: 152795

I don't think that's possible but there is an extension that you could use: https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/python-markdown

That way you can display the result (and only the result) of a python statement inside a markdown cell.

Upvotes: 2

Related Questions