@nilansh bansal's answer works great for Jupyter Notebooks. Unfortunately, it doesn't work for JupyterLab because the plugin is no longer supported (as is the case for all nbextension plugins). Since JupyterLab gains popularity, I wanted to complement the answers so far because it took me quite some time to find a solution. This is because until now there is no plugin compatible with JupyterLab. I have found the following solution for myself by combining this and this SO answers:

from IPython.display import Markdown as md
# Instead of setting the cell to Markdown, create Markdown from withnin a code cell!
# We can just use python variable replacement syntax to make the text dynamic
n = 10
md("The data consists of {} observations. Bla, Bla, ....".format(n))

Alternatively, the last line can be simplified as suggested by @Igor Fobia for Python >3.6:

md(f"The data consists of {n} observations. Bla, Bla, ....")

This leads to the desired output. However, it has the huge disadvantage that the code cell will still be visible when exporting the NB. This can be solved though:

  1. Add a tag to the code cell, i.e. name it "hide"
  2. Configure nbconvert to ignore the tagged cells, e.g. by adding this c.TagRemovePreprocessor.remove_input_tags = {"hide"} to your ~/.jupyter/jupyter_notebook_config.py config file

I have written a detailed blog-post about how I implemented this solution for publishing Notebooks on my blog. If you use JupyterLab < 2.0, you could install the jupyterlab-celltags plugin for JupyterLab to simplify the cell tagging.

Answer from mc51 on Stack Overflow
Top answer
1 of 3
63

@nilansh bansal's answer works great for Jupyter Notebooks. Unfortunately, it doesn't work for JupyterLab because the plugin is no longer supported (as is the case for all nbextension plugins). Since JupyterLab gains popularity, I wanted to complement the answers so far because it took me quite some time to find a solution. This is because until now there is no plugin compatible with JupyterLab. I have found the following solution for myself by combining this and this SO answers:

from IPython.display import Markdown as md
# Instead of setting the cell to Markdown, create Markdown from withnin a code cell!
# We can just use python variable replacement syntax to make the text dynamic
n = 10
md("The data consists of {} observations. Bla, Bla, ....".format(n))

Alternatively, the last line can be simplified as suggested by @Igor Fobia for Python >3.6:

md(f"The data consists of {n} observations. Bla, Bla, ....")

This leads to the desired output. However, it has the huge disadvantage that the code cell will still be visible when exporting the NB. This can be solved though:

  1. Add a tag to the code cell, i.e. name it "hide"
  2. Configure nbconvert to ignore the tagged cells, e.g. by adding this c.TagRemovePreprocessor.remove_input_tags = {"hide"} to your ~/.jupyter/jupyter_notebook_config.py config file

I have written a detailed blog-post about how I implemented this solution for publishing Notebooks on my blog. If you use JupyterLab < 2.0, you could install the jupyterlab-celltags plugin for JupyterLab to simplify the cell tagging.

2 of 3
36

So After going through all the links I was able to resolve the problem by referring to nbextension jupyter notebook docs : https://github.com/ipython-contrib/jupyter_contrib_nbextensions

Steps Taken:

  1. pip install jupyter_contrib_nbextensions
  2. jupyter contrib nbextension install --user
  3. jupyter nbextension enable python-markdown/main

After the above commands started a jupyter notebook and to print the value of a variable in the markdown cells works like charm!

You just have to use {{ ac_score }} within a markdown cell.

Screenshot

Thanks!

Discussions

Jupyter notebook to preview variables/types? - Part 1 (2017) - fast.ai Course Forums
Is there an easy way to preview local variables/types/values within notebooks? I finding myself typing 'print' too often to accomplish that. Thanks! Gleb More on forums.fast.ai
🌐 forums.fast.ai
0
January 4, 2017
Print name of variable and value in ipython notebook concisely - Stack Overflow
0 How to print a variable name in a print statement or any text output statement. Python, Jupyter Notebook? More on stackoverflow.com
🌐 stackoverflow.com
October 2, 2017
python - Print all variables defined in one Jupyter cell - Stack Overflow
Is there an easier way to display the name and the value of all variables defined in a single cell in a pretty way? The way I'm doing now is like this, but I waste a lot of time when there are 30 More on stackoverflow.com
🌐 stackoverflow.com
How to refer to a specific variable or output of a cell in a notebook?
Context In Jupyter Book, we’d like a language agnostic way to grab the output of a cell in a notebook, and inject it into a page in a book. However, there isn’t an obvious way to do this and we’re considering a few options. I’m curious if anybody in the JupyterLab world has an intuition ... More on discourse.jupyter.org
🌐 discourse.jupyter.org
0
0
March 5, 2022
🌐
Librarycarpentry
librarycarpentry.github.io › lc-python-intro › variables.html
Python Intro for Libraries: Variables and Types
December 18, 2025 - In Python the = symbol assigns a value to a variable. Here, Python assigns the number 42 to the variable age and the name Ahmed in single quote to a variable name. ... You can print Python objects to the Jupyter notebook output using the built-in function, print().
🌐
Fast.ai
forums.fast.ai › part 1 (2017)
Jupyter notebook to preview variables/types? - Part 1 (2017) - fast.ai Course Forums
January 4, 2017 - Is there an easy way to preview local variables/types/values within notebooks? I finding myself typing 'print' too often to accomplish that. Thanks! Gleb
🌐
GitHub
github.com › jupyter › notebook › discussions › 6708
Is there a way to get the value of a variable from a bash line of code? · jupyter/notebook · Discussion #6708
The fact that i was also the variable you used in your bash script is coincidental; IPython is not introspecting into the bash process to track the value of i. If you replace --out i with --out anything and the subsequent print(i) call with print(anything), your notebook will function identically. As to your last question about how to retrieve output from a bash script in one cell via Jupyter/IPython wizardry, your a = [for loop] approach is the most straightforward that I've used.
Author   jupyter
🌐
Wrighters
wrighters.io › home › how to view all your variables in a jupyter notebook
How to view all your variables in a Jupyter notebook - wrighters.io
April 15, 2021 - Jupyter/IPython provide three helpful magics for inspecting variables. First, there is %who. With no arguments it prints all the interactive variables with minimal formatting.
Find elsewhere
🌐
CSDN
devpress.csdn.net › python › 62fd90de7e668234661928a6.html
Print Variable In Jupyter Notebook Markdown Cell Python_python_Mangs-Python
August 18, 2022 - Answer a question Can I print the value of a variable in Markdown Cell Jupyter Notebook? Tried Code: value = 5.3 Markdown cell --> Value is {{ value }} I want that the Markdown cell should display the Mangs Python
🌐
Kaggle
kaggle.com › code › pruthvireddy › jupyter-notebook-tip-to-display-variable-info
Jupyter notebook tip to display variable info
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds
Top answer
1 of 3
7

You can use whos command to see all variables stored in the current kernel.

k, g, lx = .4, .8, 6.6
m = k*g*lx**2
whos

outputs:

Variable   Type     Data/Info
-----------------------------
g          float    0.8
k          float    0.4
lx         float    6.6
m          float    13.939200000000001

But as said, it displays all variables, so it will display other variables from earlier cells you've run.

A similar result can be achieved using locals() or globals() command from python built-in functions, which return a dictionary of variables. But the way jupyter represents is prettier.


Alternatively you can use InteractiveShell. This will change the behavior of cells and act like a python shell would, so it will output every called value (to output cell) once run.

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

k
g
... do stuff ...
lx
m
... do more stuff ...

outputs:

Out[2]: 0.4
Out[2]: 0.8
Out[2]: 6.6
Out[2]: 13.939200000000001

And finally you can return the interactivity to default by setting it to last_expr.

InteractiveShell.ast_node_interactivity = "last_expr"

But the way you do it is probably the easiest and prettiest way, you can just remove the assignment on dataframe to make it a one liner or you can make it more compact to call by:

k, g, lx, m

Out[3]: (0.4, 0.8, 6.6, 13.939200000000001)
2 of 3
6

So, this was a tough nut to crack. Essentially we are just trying to grab all of the lines in the current cell and extract the variables. As it turns out, we cannot use the global variables defined by IPython (e.g. _, __, _i<n> etc) as suggested in Programmatically get current Ipython notebook cell output? because (as far as my experiments have shown) you can only grab values from previously executed cells and not the one currently being executed.

Luckily for us, it turns out that using the magic command %history does grab the input of the current cell. So with the help of this and this I have created a function that does exactly what you want:

def cell_vars(offset=0):
    import io
    from contextlib import redirect_stdout

    ipy = get_ipython()
    out = io.StringIO()

    with redirect_stdout(out):
        ipy.magic("history {0}".format(ipy.execution_count - offset))

    #process each line...
    x = out.getvalue().replace(" ", "").split("\n")
    x = [a.split("=")[0] for a in x if "=" in a] #all of the variables in the cell
    g = globals()
    result = {k:g[k] for k in x if k in g}
    return result

You can test it with something like:

a = 1
b = 2
c = 3

cell_vars()

which should give {'a': 1, 'b': 2, 'c': 3}, you can then format this and print it however you like. Obviously there are some limitations with my line processing (assumes that all variables of interest are in global scope).

Hope this is useful!

🌐
Saturn Cloud
saturncloud.io › blog › printing-a-variable-in-jupyter-notebook-markdown-cell-using-python
Printing a Variable in Jupyter Notebook Markdown Cell using Python | Saturn Cloud Blog
September 9, 2023 - In this example, we assign a value of 10 to the variable x and print its value using the print() function. We use f-strings to format the output string and include the value of x inside curly braces.
🌐
Jupyter Community Forum
discourse.jupyter.org › jupyterlab
How to refer to a specific variable or output of a cell in a notebook? - JupyterLab - Jupyter Community Forum
March 5, 2022 - Context In Jupyter Book, we’d like a language agnostic way to grab the output of a cell in a notebook, and inject it into a page in a book. However, there isn’t an obvious way to do this and we’re considering a few optio…
🌐
Kaggle
kaggle.com › questions-and-answers › 392394
Printing variables in markdown cells
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds
🌐
SwCarpentry
swcarpentry.github.io › python-novice-gapminder › 02-variables
Plotting and Programming in Python: Variables and Assignment
May 2, 2023 - --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-c1fbb4e96102> in <module>() ----> 1 print(last_name) NameError: name 'last_name' is not defined · The last line of an error message is usually the most informative. ... Be aware that it is the order of execution of cells that is important in a Jupyter notebook, not the order in which they appear. Python will remember all the code that was run previously, including any variables you have defined, irrespective of the order in the notebook.
🌐
YouTube
youtube.com › watch
PYTHON : Print Variable In Jupyter Notebook Markdown Cell ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
TypeThePipe
typethepipe.com › vizs-and-tips › magic-whos-method-jupyter-notebook
List all the defined variables in Jupyter Notebooks | TypeThePipe
January 14, 2020 - But in case a notebook is all what you need, you have few ways to display this information. The first and easiest one is to use the magic method %whos · Two alternative ways are nbextension and Jupyter Lab variable inspector.
🌐
CodeBurst
codeburst.io › python-basics-1-hello-world-and-strings-de0d17857c93
Python Hello World and String Manipulation | by Michael Galarnyk | codeburst
November 12, 2019 - Open your terminal (Mac) or command ... get updates from this writer. ... Type the following into a cell in Jupyter and type shift + enter to execute code. # This is a one line comment print('Hello World!')...
🌐
Jupyterbook
jupyterbook.org › content › executable › output-insert.html
Store code outputs and insert into content
The following code glues a variable inside the notebook to the key "cool_text":