With the Python interactive interpreter it is easy to check Python commands. The Python interpreter can be invoked by typing the command “python” without any parameter followed by the “return” key at the shell prompt:
python
Python comes back with the following information:
Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
Once the Python interpreter is started, you can issue any command at the command prompt “>>>”.
The first thing we will do is write the mandatory “Hello World” statement:
>>> print "Hello World" Hello World
It couldn’t have been easier, could it? Oh yes, it can be written in a even simpler way. In the interactive Python interpretor the print is not necessary:
>>> "Hello World" 'Hello World' >>> 3 3 >>>
In the following example we use the interpreter as a simple calculator by typing an arithmetic expression: >>> 4.567 * 8.323 * 17 646.18939699999999 >>> You might be surprised, if you type in the following:
>>> 12 / 7 1 >>>
Python assumes that you are interested in integer division, because both divisor and dividend are integers. So the result is an integer again. The easiest way to get an exact result is by making one of the values a float by adding a “.0”:
>>> 12.0 / 7 1.7142857142857142 >>>
Alternatively you can cast one or both arguments:
>>> float(12) / 7 1.7142857142857142 >>>
Python follows the usual order of operation in expression. The standard order of operations is expressed in the following enumeration:
- exponents and roots
- multiplication and division
- addition and subtraction
This means that we don’t need parenthesis in the expression “3 + (2 * 4):
>>> 3 + 2 * 4 11 >>>
The most recent output value is automatically stored by the interpreter in a special variable with the name “_”. So we can print the output from the recent example again by typing an underscore after the prompt:
>>> _ 11 >>>
The underscore can be used in other expressions like any other variable:
>>> _ * 3 33 >>>
To close the Python interactive interpreter in Linux type Ctrl-D