Python Programming/Interactive mode

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

← Setting it up| Creating Python programs →

Python has two basic modes: The normal "mode" is the mode where the scripted and finished .py files are run in the python interpreter. Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole.

To get into interactive mode, simply type "python" without any arguments. This is a good way to play around and try variations on syntax. Python should print something like this:

$ python
Python 2.3.4 (#2, Aug 29 2004, 02:04:10) 
[GCC 3.3.4 (Debian 1:3.3.4-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

(If Python wouldn't run, make sure your path is set correctly. See Getting Python.)

The >>> is Python's way of telling you that you are in interactive mode. In interactive mode what you type is immediately run. Try typing 1+1 in. Python will respond with 2. Interactive mode allows you to test out and see what Python will do. If you ever feel the need to play with new Python statements, go into interactive mode and try them out.

A sample interactive session:

>>> 5
5
>>> print 5*7
35
>>> "hello" * 4
'hellohellohellohello'
>>> "hello".__class__
<type 'str'>

However, you need to be careful in the interactive environment. If you aren't careful, confusion may ensue. For example, the following is a valid Python script:

if 1:
  print "True"
print "Done"

If you try to enter this, as written in the interactive environment, you might be surprised by the result:

>>> if 1:
...   print "True"
... print "Done"
  File "<stdin>", line 3
    print "Done"
        ^
SyntaxError: invalid syntax

What the interpreter is saying is that the indentation of the second print was unexpected. What you should have entered was a blank line, to end the first (i.e., "if") statement, before you started writing the next print statement. For example, you should have entered the statements as though they were written:

if 1:
  print "True"

print "Done"

Which would have resulted in the following:

>>> if 1:
...   print "True"
...
True
>>> print "Done"
Done
>>>
Previous: Setting it up Index Next: Creating Python programs
Personal tools