2

I'd like to print all the variables and their values defined in a cell without having to do

print('x:', x)
print('y:', y)
print('z:', z)

... is there something like: %p x y z and it will do the equivalent of the above?

eyeApps LLC
  • 643
  • 4
  • 10

3 Answers3

1

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]
  • This actually answers the OP's question. Just to make it work in Python 3 and to print the variable name as well, I changed the last line to `print(key,": ", globals()[key])` – rouckas Oct 14 '21 at 08:39
1

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

Yale Newman
  • 1,141
  • 1
  • 13
  • 22
0
x = 'test1'
y = 'test2'
z = 'test3'

print('x: %s, y: %s, z: %s'%(x, y,z))

if x, y, z variables is integers, You should use %d instead of %s.

멍개-mung
  • 470
  • 5
  • 10