Python Programming/Interactive mode


Python has two basic modes: script and interactive. 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.

Interactive mode is a good way to play around and try variations on syntax.

On macOS or linux, open a terminal and simply type "python". On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.

Python should print something like this:

$ python
Python 3.0b3 (r30b3:66303, Sep  8 2008, 14:01:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

(If Python doesn't run, make sure it is installed and 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" * 2
'hellohello'
>>> "hello".__class__
<type 'str'>

However, you need to be careful in the interactive environment to avoid confusion. 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. You should have entered 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
>>>

Interactive mode edit

Instead of Python exiting when the program is finished, you can use the -i flag to start an interactive session. This can be very useful for debugging and prototyping.

python -i hello.py


For i in range(-1,-5,-1):

   print(i)