Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python what is it called when you see the output of a variable without printing it?

Tags:

python

In Python you can see the value of a variable without printing it, like:

>>> a = 'hello world'
>>> a
hello world

This is different from printing print(a), yet I'm still able to see a similar output. What it the technical term for this type of variable printing?

As an example of the difference, below shows how a Jupyter Notebook prints a dataframe for both types of printing:

enter image description here

like image 202
Nic Scozzaro Avatar asked Nov 16 '19 20:11

Nic Scozzaro


3 Answers

You're executing code in a REPL; the P stands for "print".

It's being implicitly printed by the console.

like image 60
Carcigenicate Avatar answered Nov 15 '22 02:11

Carcigenicate


It's not Python but the Python shell's (IDLE) behavior you're seeing. The way it's built, it prints the type or value of the item you specify. The actual Python would be to have this code inside a .py file:

a = 'hello world'
a

and you do python test.py then you'd see nothing, because the value returned by a would be silently discarded. The cli works as if there's an implicit print() statement there.

like image 39
ankush981 Avatar answered Nov 15 '22 03:11

ankush981


What you are seeing if the repr of the last expression returned by the interpreter to the global namespace in interactive mode. This is fundamentally different from the a print output, although they do go to the same stream.

For simple objects such as integer they look the same.

>>> x = 1
>>> print(x)
1
>>> x
1

The difference is that print send the string representation of the object to the STDOUT. Inputting a variable and hitting enter shows you the repr of the object. To me the big difference is that the later can be easily captured by adding an assignment to the expression, i.e. y = x. While the print output is more complicated to capture.

That is why I use the phrase "returns the value for x" or "returns x". This indicates that if you wanted to capture the return as another variable, you could.

Here is a short example to show the difference between print and repr.

>>> class Foo:
...     def __repr__(self):
...         return f'<Foo at 0x{id(self):x}>'
...     def __str__(self):
...         return 'Foo-object'
... 
>>> f = Foo()
>>> print(f)
Foo-object
>>> f
<Foo at 0x17416af3c18>
like image 36
James Avatar answered Nov 15 '22 03:11

James