Python Interpreter

You write your Python code in a text file with a name like hello.py. How does that code Run? There is program installed on your computer named "python3" or "python", and its job is looking at and running your Python code. This type of program is called an "interpreter".

Talk To The Interpreter

One benefit of the interpreter is that you can start an interactive session with the interpreter and type Python code right into it to see what it does. This is a great way to try out code ideas.

For example, what happens if you use + with strings or with lists? Here is an interpreter session trying + that way. The >>> is the prompt, the bold text is what you type, followed by the interpreter's response on the next line.

>>> 'hello' + '!'
'hello!'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> 

You could look up the formal description of +, but just typing an experiment in the interpreter to see what it does is quick and satisfying.

Incidentally, >>> examples like the above are used throughout these pages to show phrases of Python code with their output. You can always start your own interpreter session to replicate and play with these experiments yourself.

How To Get An Interpreter

There are 2 easy ways to get the interpreter:

1. Open a command-line terminal. Mac: run the "Terminal" app in the Utilities folder. Windows: type "powershell" in the lower left, this opens the Windows command line terminal. In the terminal type the command "python3" ("python" on Windows, or sometimes "py"). This runs the interpreter program directly. On the Mac type ctrl-d to exit (on Windows ctrl-z).

2. If you have PyCharm installed, at the lower-left of any window, click the Python Console tab. Or use the Tools > Python Console menu item to open an interpreter window within PyCharm.

Working With The Interpreter

The interpreter prints a >>> prompt and waits for you to type some Python code. It reads what you type, evaluates it, and prints the result — the so called read-eval-print loop (here what the user types is shown in bold)

>>> 1 + 2 * 3
7
>>> 'hello' + 'there'
'hellothere'
>>> max(1, 5, -2)
5
>>> 'hello' + 2
TypeError: can only concatenate str (not "int") to str
>>> 'hello' + str(2)
'hello2'
>>>

This is an excellent way to experiment with Python features to see how they work. If you have some code you are thinking about, it can be quick and informative to fire up the interpreter, and type the code in to see what it does. When you have an expression that works in the interpreter, you can copy/paste it into your program as a first draft of that line.

When you write a Python program, you store your code in a file like hello.py, where you can write and revise a series of functions and comments and whatnot over many lines, like writing a paper. You would not want to write a whole program at the >>> prompt, which works best for little throw-away phrases.

Indent In Interpreter

It's possible to write multi-line indented code in the interpreter. If a line is not finished, such as ending with ":", typing the return key does not run the code right away. You can write further indented lines. When you enter a blank line, the interpreter runs the whole thing. (For throw-away code like this, I am willing to indent just 2 spaces).

>>> for i in range(10):
...   mult = i * 100
...   print(i, mult)
... 
0 0
1 100
2 200
3 300
4 400
5 500
6 600
7 700
8 800
9 900

Interpreter Hacks: dir help

What are all the functions that the str type has? You could look it up, but it's also possible in the interpreter to pull the list of function names directly out of Python this (str is the name of the built-int string type):

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

The above is not the most pretty form of the data, as we're just dumping the names of Python's internal structure. Names that begin with 2 underbars like __add__ are special internal functions that code does not normally need to know about. You can see regular functions like lower() and 'find()` in the list.

With the special help function, you can pull up the PyDoc for each function (the triple-quote comments for a function). To refer to a function within the str type use the form str.find. Note that the function name is not followed by parenthesis - this is the unusual case of referring to a function but not calling it.

>>> help(str.find)
find(...)
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

 

Copyright 2020 Nick Parlante