Python Programming/Interactive mode
< Python ProgrammingPython has two basic modes: normal 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.
To start 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 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 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 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
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