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:
You're executing code in a REPL; the P stands for "print".
It's being implicitly printed by the console.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With