When we first looked at interactive Python in the section called “Command-Line Interaction” we noted that Python executes assignment statements silently, but prints the results of an expression statement. Consider the following example.
>>>pi=355/113.0>>>area=pi*2.2**2>>>area15.205309734513278
The first two inputs are complete statements, so there is no response. The third input is just an expression, so there is a response.
It isn't obvious, but the value assigned to pi
isn't correct. Because we didn't see anything displayed, we didn't get any
feedback from our computation of pi.
Python, however, has a handy way to help us. When we type a simple
expression in interactive Python, it secretly assigns the result to a
temporary variable named _. This isn't a part of
scripting, but is a handy feature of an interactive session.
This comes in handy when exploring something rather complex.
Consider this interactive session. We evaluate a couple of expressions,
each of which is implicitly assigned to _. We can then
save the value of _ in a second variable with an
easier-to-remember name, like pi or
area.
>>>335/113.02.9646017699115044>>>355/113.03.1415929203539825>>>pi=_>>>pi*2.2**215.205309734513278>>>area=_
Note that we created a floating point object (2.964...), and Python
secretly assigned this object to _. Then, we computed a
new floating point object (3.141...), which Python assigned to
_. What happened to the first float, 2.964...? Python
garbage-collected this object, removing it from memory.
The second float that we created (3.141) was assigned to
_. We then assigned it to pi, also,
giving us two references to the object. When we computed another
floating-point value (15.205...), this was assigned to
_. Does this mean our second float, 3.141... was
garbage collected? No, it wasn't garbage collected; it was still
referenced by the variable pi.