Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Interactive Mode Revisited

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.





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.






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.

  Published under the terms of the Open Publication License Design by Interspire