Quick Cheats[-][--][++]


#!/usr/bin/env python

# Tuples (like lists but immutable)
# ---------------------------------
mytuple = (1, 2, 'three')
print len(mytuple)
print mytuple[0]
#tuple[2] = 'hi' #error, immutable

def Foo():
    tuple = ('one', 'two')
    return tuple

test = Foo()
print test

(one, two) = Foo()
print one
print two

# List Comparisons
# ----------------
strs = ['hello', 'and', 'goodbye']
print strs
shout = [s.upper() + '!!!' for s in strs]
print shout

fruits = ['apple', 'cherry', 'bannana', 'lemon']
print fruits
afruits = [ s.upper() for s in fruits if 'a' in s ]
print afruits

# Dict
# ----
dict = {'key1':'value1', 'key2':'value2'}
print dict
print dict['key2']
dict['key2'] = 'newvalue2'
print dict['key2']
#print dict['dne'] #prints error
print dict.get('dne') #prints None
if 'dne' in dict: print dict['dne']

print "# List Keys"
for key in dict: print key
for key in dict.keys(): print key
print dict.keys() #A List

print "# List Values"
for key in dict: print dict[key]
print dict.values() #A list

print "# List key value (space separated)"
for key in sorted(dict.keys()): print key, dict[key]
for k, v in dict.items(): print k, v

# .items() is the dict expressed as (key, value) tuples
print dict.items() # [('key1', 'value1'), ('key2', 'value2')]

print "# Dict Formatting"
print 'The dicts values are %(key1)s and %(key2)s' % dict

Introduction[-][--][++]

Print output[-][--][++]

Print will always add a newline char, unless you put a comma after it
so in a loop, print a will print a on each line, while print a, will have no new lines

Operators[-][--][++]


+  contac strings, or add numbers

= (assignment)
== (equal to)
>
<
>=
<=

Convert[-][--][++]

float(a) #converts a to float
int(a)   #converts a to integer
long(a)  #converts a to long
str(a)   #converts a to string

Strings[-][--][++]

  1. strings can be ' or "
    'doesn\'t'
    "doesn't"
    'He said "Yes"'
    
  2. multiple lines with backslash
  3. or multiple lines can be enclosed with """ or '''
  4. you can ignore \n by using raw strings (this will print \n\ with it)
    hello = r"This is a rather long string containing\n\
    several lines of text much as you would do in C."
    
  5. Concatenate with + and multiply strings with *
    word = 'HI ' + 'There'
    word*5 #prints Hi There five times
    
  6. string subscripted
     
    word = HelpA
    word[4] #A
    word[0:2] #He
    word[2:4] #lp
    word[:2] #He
    word[2:] #lpA
    word[-1] #A
    word[-2] #p
    word[-2:] #pA
    word[:-2] #Hel
    word[-100:] #HelpA
    word[-10] # error
    word[0] = x # ERROR, words cannot be changed ('x' + word[1:] is good)
    
  7. length len(word)

Lists[-][--][++]

Each element is its own type, string int double...

Basic[-][--][++]

a = ['spam', 'eggs', 100, 1234]
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

You can edit its values[-][--][++]

>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

Assignments[-][--][++]

>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]

Length[-][--][++]

>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4

Nested Lists[-][--][++]

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra')     # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']

First Steps[-][--][++]

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print b
...     a, b = b, a+b
...
1
1
2
3
5
8

More Control Flow Tools[-][--][++]

IF[-][--][++]

>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...      x = 0
...      print 'Negative changed to zero'
... elif x == 0:
...      print 'Zero'
... elif x == 1:
...      print 'Single'
... else:
...      print 'More'
...
More

For[-][--][++]

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print x, len(x)
...
cat 3
window 6
defenestrate 12

To modify the list

>>> for x in a[:]: # make a slice copy of the entire list
...    if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']

Range[-][--][++]

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb

More loops here http://docs.python.org/tutorial/datastructures.html#tut-loopidioms

Break and Continue[-][--][++]

The break statement, like in C, breaks out of the smallest enclosing for or while loop.
The continue statement, also borrowed from C, continues with the next iteration of the loop.

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

Pass[-][--][++]

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

>>> class MyEmptyClass:
...     pass
...

Functions[-][--][++]

The first statement of the function body can optionally be a string literal; this string literal is the function's documentation string, or docstring

>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print a,
...         a, b = b, a+b
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Assign as new name[-][--][++]

since fib does not return anything, you can assign the actual function to another variable \
kinda like a function alias

>>> fib

>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

Returns[-][--][++]

functions without return, actually return 'None'

>>> fib(0)
>>> print fib(0)
None

>>> def fib2(n): # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # see below
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Default Values[-][--][++]

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise IOError('refusenik user')
        print complaint

The default values are evaluated at the point of function definition in the defining scope, so that

i = 5
def f(arg=i):
    print arg
i = 6
f() # will print 5

Important Warning
The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print f(1) # [1]
print f(2) # [1, 2]
print f(3) # [1, 2, 3]

IF you don't want this behavior then:
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

Keyword Arguments[-][--][++]

You don't have to call parameters in order, if you reference it's keyword

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print "-- This parrot wouldn't", action,
    print "if you put", voltage, "volts through it."
    print "-- Lovely plumage, the", type
    print "-- It's", state, "!"

parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')

When a final formal parameter of the form name is present, it receives a dictionary (see Mapping Types ââ¬â dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before name.) For example, if we define a function like this:

def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments: print arg
    print "-" * 40
    keys = keywords.keys()
    keys.sort()
    for kw in keys: print kw, ":", keywords[kw]

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")

#WOULD PRINT OUT
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

Arbitrary Argument Lists[-][--][++]

Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))