The Python Interpreter
The Python interpreter
is a program that reads Python program statements and executes them immediately (see [8] for full documentation). To use the interpreter, you need to open a terminal window or command prompt on your workstation. The interpreter operates in two modes.1
Interactive Mode
You can use the interpreter as an interactive tool. In interactive mode, you run the Python program and you will see a new prompt, >>>, and you can then enter Python statements one by one. In Microsoft Windows, you might see something like this:
C:UsersPaul>python
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> _
The interpreter executes program statements immediately. Interactive mode is really useful when you want to experiment or try things out. For example, sometimes you need to see how a particular function (that you haven’t used before) behaves. On other occasions, you might need to see exactly what a piece of failing code does in isolation.
The >>> prompt can be used to enter one-line commands or code blocks that define classes or functions (discussed later). Some example commands are shown here:
1 >>> dir(print)
2 ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__','__name__','__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
3 >>>
4 >>> 123.456 + 987.654
5 1111.11
6 >>>
7 >>> 'This'+'is'+'a'+'joined'+'up'+'string.'
8 'Thisisajoinedupstring.'
9 >>>
10 >>> len('Thisisajoinedupstring.')
11 22
The
dir()
command on line 1 lists all the attributes of an object, helpful if you need to know what you can do with an object type. dir() run without an argument tells you what modules you have available. dir(print) shows a list of all the built-in methods for print(), most of which you’ll never need.
If you type an expression value, as on line 4, 123.456 + 987.654 the interpreter will execute the calculation and provide the result. The expression on line 7 joins the strings of characters into one long string. The
len()
function on line 10 gives you the length of a string in characters.
If you define a new function2 in interactive mode, the interpreter prompts you to complete the definition and will treat a blank line as the end of the function.
1 >>> def addTwoNumbers(a,b):
2 ... result = a + b
3 ... return result
4 ...
5 >>> addTwoNumbers(3,6)
6 9
7 >>>
Note that when the interpreter expects more code to be supplied in a function, for example, it prints the ellipsis prompt (...). In the case of function definitions, a blank line (see line 4 above) completes the function definition.
We define the function in lines 1 through 3 (note the indentation
), and the blank line 4 ends the definition. We call the function on line 5 and add 6 + 3, and the result is (correctly) 9.
One other feature of the interactive interpreter is the help() function. You can use this to see the documentation of built-in keywords and functions. For example:
>>>
help(open)
Help on built-in function open in module io:
open(...)
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -> file object
... etc. etc.
Note
The Python interactive interpreter is really handy to try things out and explore features of the language.
Command-Line Mode
In command-line mode
, the Python program is still run at the command line but you add the name of a file (that contains your program) to the command:
python myprogram.py
The interpreter reads the contents of the file (myprogram.py in this case), scans and validates the code, compiles the program, and then executes the program. If the interpreter encounters a fault in the syntax of your program, it will report a compilation error. If the program fails during execution, you will see a runtime error. If the program executes successfully, you will see the output(s) of the program.
You don’t need to worry about how the interpreter does what it does, but you do need to be familiar with the types of error messages it produces.
We use command-line mode to execute our programs in files.
Coding, Testing and Debugging Python Programs
The normal sequence of steps when creating a new program is as follows:
- 1.Create a new .py file that will contain the Python program (sometimes called source code).
- 2.Edit your .py file to create new code (or amend existing code) and save the file.
- 3.Run your program at the command prompt to test it, and interpret the outcome.
- 4.If the program does not work as required, or you need to add more features, figure out what changes are required and go to Step 2.
It’s usually a good idea to document your code with comments. This is part of the editing process, Step 2. If you need to make changes to a working program, again, you start at Step 2.
Writing new programs is often called
coding
. When your programs don’t work properly, getting programs to do exactly what you want them to do is often called
debugging
.
Comments, Code Blocks, and Indentation
Python, like all programming languages has conventions that we must follow. Some programming languages use punctuation such as braces ({}) and semicolons (;) to structure code blocks. Python is somewhat different (and easier on the eye) because it uses white space and indentation to define code structure.3 Sometimes code needs a little explanation, so we use comments to help readers of the code (including you) understand it.
We introduce indentation
and comments
with some examples.
#
# some text after hashes
#
brdr = 2 # thick border
| Any text that appears after a hash character (#) is ignored by the interpreter and treated as a comment. We use comments to provide documentation. |
def my_func(a, b, c): d = a + b + c
...
...
if this_var==23:
doThis()
doThat()
...
else:
do_other()
...
| The colon character
(:) denotes the end of a header line that demarks a code block. The statements that follow the header line should be indented. Colons are most often used at the end of if, elif, else, while, and for statements, and function definitions (that start with the def keyword). |
def addTwoNumbers(a, b):
"adds two numbers"
return a + b
| In this example the text in quotes is a docsctring. This text is what a help(addTwoNumbers) command would display in the interactive interpreter. |
if long_var is True &&
middle==10 &&
small_var is False:
...
...
| The backslash
character () at the end of the line indicates that the statement extends onto the next line. Some very long statements might extend over several lines. |
xxxxxxxxxxxxxx:
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxx:
xxxxxxxxxxx:
xxxxxxx
xxxxxxxxxxx:
xxxx
xxxx
| All code blocks are indented once a header line with a colon appears. All the statements in that block must have the same indentation. Code blocks can be nested within each other, with the same rule: All code in a block has the same indentation. Indentation is most often achieved using four-space increments. |
a = b + c ; p = q + r
a = b + c
p = q + r
| The semicolon character
(;) can be used to join multiple statements in a single line. The first line is equivalent to the two lines that follow it. |
Variables
A
variable
is a named location in the program’s memory that can be used to store some data. There are some rules for naming variables:
- The first character must be a letter or underscore ( _ ).
- Additional characters may be alphanumeric or underscore.
- Names are case-sensitive.
Common Assignment Operations
When you store data in a variable it is called assignment. An assignment
statement places a value or the result of an expression into variable(s). The general format of an assignment is:
var = expression
An
expression
could be a literal, a calculation, a call to a function, or a combination of all three. Some expressions generate a list of values; for example:
var1, var2, var3 = expression
Here are some more examples:
>>> # 3 into integer myint
>>> myint = 3
>>>
>>> # a string of characters into a string variable
>>> text = 'Some text'
>>> # a floating point number
>>> cost = 3 * 123.45
>>> # a longer string
>>> Name = 'Mr' + ' ' + 'Fred' + ' ' + 'Bloggs'
>>> # a list
>>> shoppingList = ['ham','eggs','mushrooms']
>>> # multiple assignment (a=1, b=2, b=3)
>>> a, b, c = 1, 2, 3
Other Assignment Operations
Augmented assignment
provides a slightly shorter notation, where a variable has its value adjusted in some way.
This assignment | Is equivalent to |
---|---|
x+=1
x-=23
x/=6
x*=2.3
|
x = x + 1
x = x – 23
x = x / 6
x = x * 2.3
|
Multiple assignment provides a slightly shorter notation, where several variables are given the same value at once.
This assignment | Is equivalent to |
---|---|
a = b = c = 1
|
a = 1
b = 1
c = 1
|
So-called multuple assignment
provides a slightly shorter notation, where several variables are given their values at once.
This assignment | Explanation |
---|---|
x, y, z = 99, 100, 'OK'
p, q, r = myFunc()
| Results in:
x=99, y= 100, and z='OK'
If myFunc() returns three values, p, q, and r are assigned those three values. |
Python Keywords
Like all programming languages, in Python, some words have defined meanings and are reserved for the Python interpreter. You must not use these words as variable names. Note that they are all lowercase.
and
|
as
|
assert
|
break
|
class
|
continue
|
def
|
del
|
elif
|
else
|
except
|
exec
|
finally
|
for
|
from
|
global
|
if
|
import
|
in
|
is
|
lambda
|
not
|
or
|
pass
|
print
|
raise
|
return
|
try
|
while
|
with
|
yield
|
There are a large number of built-in names that you must not use, except for their intended purpose. The cases of True, False, and None are important. The most common ones are listed here.
True
|
False
|
None
|
abs
|
all
|
any
|
chr
|
dict
|
dir
|
eval
|
exit
|
file
|
float
|
format
|
input
|
int
|
max
|
min
|
next
|
object
|
open
|
print
|
quit
|
range
|
round
|
set
|
str
|
sum
|
tuple
|
type
|
vars
|
zip
|
To see a list of these built-ins, list the contents of the __builtins__ module in the shell like this:
>>> dir(__builtins__)
Special Identifiers
Python also provides some special identifiers that use underscores. Their name will be of the form:
_xxx
__xxx__
__xxx
Mostly, you can ignore these.4 However, one that you might encounter in your programming is the special system variable:
__name__
This variable specifies how the module was called. __name__ contains:
- The name of the module if imported.
- The string '__main__' if executed directly.
You often see the following code at the bottom of modules. The interpreter loads your program and runs it if necessary.
if __name__ == '__main__':
main()
Python Modules
Python code is usually stored in text files that are read by the Python interpreter at runtime. Often, programs get so large that it makes sense to split them into smaller ones called modules. One module
can be imported into others using the import statement.
import othermod # makes the code in
othermod
import mymodule # and
mymodule
available
Typical Program Structure
The same program or module structure
appears again and again, so you should try and follow it. In this way, you know what to expect from other programmers and they will know what to expect from you.
#!/usr/bin/python
| Used only in Linux/Unix environments (tells the shell where to find the Python program). |
#
# this module does
# interesting things like
# calculate salaries
#
| Modules should have some explanatory text describing or documenting their behavior. |
from datetime import datetime
| Module imports come first so their content can be used later in the module.
|
now =
datetime.now()
| Create a global variable that is accessible to all classes and functions in the module. |
class bookClass(object):
"Book object"
def __init__(self,title):
self.title=title
return
| Class definitions appear first. Code that imports this module can then use these classes.
|
def testbook():
"testing testing..."
title="How to test Py"
book=bookClass(title)
print("Tested the book")
| Functions are defined next. When imported, functions are accessed as module.function(). |
if __name__=='__main__':
testBook()
| If imported, the module defines classes and functions. If this module is run, the code here (e.g., testBook()) is executed. |
Footnotes
4
The only ones you really need to know are the __name__ variable and the __init__() method called when a new object is created. Don’t start your variable names with an underscore and you’ll be fine.