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
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
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.

>>> 
pi=355/113.0

>>> 
area=pi*2.2**2

>>> 
area

15.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.0

2.9646017699115044
>>> 
355/113.0

3.1415929203539825
>>> 
pi=_

>>> 
pi*2.2**2

15.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.


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