Python Reference

Conditionals

if a:
    print "Hello"
elif b:
   print "Goodbye"
else:
  print "I have nothing to say"

Loops

for char in 'aeiou':
    print(char)

while i < 4:
   i += 1
   print i

Functions

def normalize(value, factor=1.0):
    """Normalize positive values,
    truncating negative ones."""
    if value < 0.0:
        return 0.0
    return value * factor

Types

intx = 1; x = int('1')
floatx = 1.0; x = float(1)
complexx = 1 + 2j
stringx = "s"
booleanx = True; y = False

Arithmetic

addition1 + 2.03.0
subtraction2 - 3-1
multiplication2 * 36
division2 / 31
modulo3 % 21

Lists

initializeL = [2, 1, 3, 4, 8, 9]
appendL.append(5)
sortL.sort()
removeL.remove(5)

Strings

initializes = "acc ttg cta tcg"
splits.split()['acc', 'ttg', 'cta', 'tcg']
join" ".join(["a", "b"])"a b"
finds.find('ttg')4
counts.count('t')4
strip' a '.strip()'a'

File I/O

openf = open(filename, 'r')or 'w' to write
writef.write("Hello world")
read all linesf.readlines()
read the next linel = f.readline()

Indexing

'abcd'[-1]
index'abcd'[1]'b'
negative index'd'
lengthlen('abcd')4
slice'abcd'[1:3]'bc'

String Formatting

"Hello %s" % 'name!'"Hello name!"
"%d, %0.2f" % (2, 0.3456)"2 0.35"

Importing Libraries

from foo import bar
import foo.bar