StatementsΒΆ

Statements must end in a newline:

print "I am a statement"

The # character marks the beginning of a comment:

print "I am a statement with a comment"  # this is a comment

Indentation is used after statements that end with a colon (:):

if x == 1:
    print "Found number 1"

Indentation is significant. The amount of indentation is up to you (4 spaces is standard for Python), but you must be consistent. The indentation level is what distinguishes blocks of code, determining which code is part of a function or which code repeats in a while loop, for example:

print "I am a statement"
    print "I am a statement at a different indentation level"  # this is an error

Branching is supported via if, elif, and else:

if x == 1:
    print "Found number 1"
elif x == 2:
    print "Found number 2"
else:
    print "Did not find 1 or 2"

y = 3 if x == 1 else 4  # Ternary form is acceptable

Looping is supported via while:

x = 10
while x > 0:
    print x
    x = x - 1

Looping is also supported via for:

myTuple = ("A", True, 3)

# for will step through tuples or byte lists
for element in myTuple:
    print element

# for will step through iterators returned by xrange
# the following prints "012" (note that SNAPpy does not insert spaces)
for number in xrange(3):
    print number

# for will step through strings
for letter in myStringVariableOrConstant:
    if letter == "Z":
        print "I found a Z"