Quick Python Syntax Tips


For readers who are somewhat unfamiliar with Python programming, the following list contains a few basic tips to quickly understand the Python code syntax used in this Learning Path. For a more complete introduction, you may also want to consult The Informal Introduction to Python.


Single-line comments begin with the pound (#) character, and end with a new line character. Multi-line comments are surrounded by three single (or double) quotes:

someVariable = 4 # This assigns 4 to someVariable.

''' There are multiple lines 
in this comment. '''



Strings can be contained in pairs of either single- or double-quote characters, and can be concatenated with the + operator. The str() function attempts to convert its input into a string representation.

myString1 = 'some' + ' string'
myString2 = "another " + "string"

print 'four: ' + str(4) 
# 'four: 4'


Lists, denoted by a pair of square brackets, are equivalent to dynamic arrays. The starting index in a list is 0. To add to a list, use the append() function. The len() function returns the length of a list.

myList = []

print myList[1] 
# 'oranges'

print str( len( myList ) ) 
# '2'


Dictionaries are denoted by pairs of curly brackets, and contain key-value pairs (where the key is a hashable object, like a string).

myDictionary = {}
myDictionary['myKey'] = 'myValue'
myDictionary['myOtherKey'] = 17

print str( myDictionary['myOtherKey'] ) 
# '17'

print str( myDictionary ) 
# '{'myKey': 'myValue', 'myOtherKey': 17}'


Tuples are immutable sequences denoted by pairs of parentheses. You may refer to an element within a tuple according to its index. The first element in a tuple is indexed at zero [0].

myTuple = ('pants', 'shirt', 1987)

print str( myTuple[1] )
# 'shirt'

print str( myTuple )
# ('pants', 'shirt', 1987)

Classes, Functions, and Indentation

Consistent indentations are used to identify class, function, and statement bodies such as if/else conditions, and for loops. In the code samples we present, one level of indentation consists of four space (' ') characters. Classes are declared using the 'class' keyword, while methods and global functions are declared using the 'def' keyword. Note that the first parameter (usually named 'self') of class methods refers to the current instance.

class myClass:
    def __init__(self):
        __init__ identifies the class constructor. 
        pass # The 'pass' keyword indicates that we do nothing.

    def doIt(self, myParameter):
        This is a method which we have defined as having one
        parameter whose name is myParameter.
        for i in range(0, 9): # This will loop 10 times.
            if (i == 0):
                # Print 'Hello World!' on the first iteration
                print 'Hello World!'
                # Print a string representation of myParameter the rest of the time.
                print str( myParameter )

# This code will be executed once the myClass definition is read.
myClassInstance = myClass()
myClassInstance.doIt( 'some string' )

Exception Handling

Conventional try/catch/finally exception handling is performed using the 'try' and 'except' keyword sequence. The 'else' and 'finally' keywords are optional. The code following the 'else' keyword is executed if the code following the 'try' keyword executes without exception. The code following the 'finally' keyword is executed regardless of the occurrence of an exception. Note that you can throw your own exceptions using the 'raise' keyword.

# This code sample can be found at: http://docs.python.org/tutorial/errors.html
def divide(x, y):
        result = x / y
    except ZeroDivisionError:
        print "division by zero!"
        print "result is" + result
        print "executing finally clause"