@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:
- Add a tag to the code cell, i.e. name it "hide"
- Configure
nbconvertto ignore the tagged cells, e.g. by adding thisc.TagRemovePreprocessor.remove_input_tags = {"hide"}to your~/.jupyter/jupyter_notebook_config.pyconfig 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.
@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:
- Add a tag to the code cell, i.e. name it "hide"
- Configure
nbconvertto ignore the tagged cells, e.g. by adding thisc.TagRemovePreprocessor.remove_input_tags = {"hide"}to your~/.jupyter/jupyter_notebook_config.pyconfig 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.
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:
- pip install jupyter_contrib_nbextensions
- jupyter contrib nbextension install --user
- 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!
Jupyter notebook to preview variables/types? - Part 1 (2017) - fast.ai Course Forums
Print name of variable and value in ipython notebook concisely - Stack Overflow
python - Print all variables defined in one Jupyter cell - Stack Overflow
How to refer to a specific variable or output of a cell in a notebook?
Videos
You can create a line magic which will do that.Something like below
from IPython.core.magic import register_line_magic
@register_line_magic
def p(args):
for key in args.split(" "):
print globals()[key]
With ipython notebook you can use:
#without turning on %automagic
%who
#with turning on %automagic
who
This will display all variables names held in memory
#without turning on %automagic
%whos
#with turning on %automagic
whos
This will display variable names and their values
References:
iPython Magic
Relevant StackOverflow Question
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)
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!
Since you are already using f-strings, I would make the dataframe column headers variables, so the print statement is updated each time:
x_col = "var1"
y_col = "var2"
x = df[x_col]
y = df[y_col]
cor = x.corr(y)
print(f"The Correlation between {x_col} and {y_col} is: {cor:1.2f}" )
There are multiple ways to print variables in string. You can do following code:
print("The Correlation between "+x+" and "+y+" is: %1.2f"%cor )
or
print("The Correlation between {} and {} is: {}".format(x,y,cor))
Hope this helps