Python Statements

A Python script consists of a series of statements and comments. Each statement is a command that is recognized by the Python interpreter and executed. Statements are usually one line long, though there are a few ways to make them extend over several lines.

A comment begins with the # sign and can appear anywhere (outside of strings). Everything from the # to the end of the line is ignored by the Python interpreter. Commonly used for human-readable notes.

Some Statements

sum = 2 + 2  # this is a statement

name = raw_input("What is your name?")  # these are two statements
print "Hello,", name

print "Did you know that your name has", \
      len(name), "letters?"  # This is one statement spread across 2 lines

# Another way to extend a statement across several lines
print "Here is your name repeated 7 times:", (
      name * 7

The Python interpreter will start at the top of the file and make sure the program is valid Python. (If not it will give an error message.) After that it executes each statement in order, starting from the top. It stops when it reaches the end of the file or if there is an uncaught exception.


It is common to group statements into blocks using indentation. This is similar to what most people do when they write instructions. You can execute the entire block conditionally or turn it into a function that can be called from many different places.

Example blocks:

sequence = raw_input("Enter a DNA sequence:")
if EcoRI in sequence:
    print "Sequence contains an EcoRI site"  # This is a one-line block

import sys
sequence2 = raw_input("Enter another sequence:")
if len(sequence2) < 100:
    print "Sequence is too small.  Throw it back."  # a two-line block

sequences = (sequence, sequence2)
for seq in sequences:
    print "sequence length =", len(seq)  # a block ...
    for c in "ATCG":
      print "#%s = %d" % (c, seq.count("C"))  # ... with a block inside it

If statements

The if statement is a conditional statement. If the expression is true, execute the statements in the next block.

>>> if 5 > 4:
...     print "5 is larger"
5 is larger
If the expression is false and there is an else: block, execute those statements instead.

>>> if 4 > 5:
...     print "4 is larger"
... else:
...     print "5 is larger"
5 is larger

This page based on Perl Statements

Andrew Dalke
Last modified: Tue Feb 3 12:22:05 SAST 2004