Python

Overall
  • Indendation matters!
  • Python is case sensitive
  • Comments: # , or """multiline comment """

  • a=b=c=1 defines a, b, and c to be 1
  • a,b,c = 1, 1.0, "Hello Glorious World"

  • Logical
    ==, !=, <, >, <=, >-
    and, or, not
    in, not in
    is, is not (x is y, here is results in 1 if id(x) equals id(y).)
    In general, 0 is FALSE, and all other numbers are TRUE
    - x or y
    - x and y
    - not x
    Arithmatic
    +, -, *, /
    % (remainder), ** (exponent), // (floor division)
    Assignment Operators
    = Simple assignment
    c += a is equivalent to c = c + a
    c -= a is equivalent to c = c - a
    c *= a is equivalent to c = c * a
    c /= a is equivalent to c = c / a
    c %= a is equivalent to c = c % a
    c **= a is equivalent to c = c ** a
    c //= a is equivalent to c = c // a
    Conditional Assignment
    x = 3 if (y == 1) else 2
    x = 3 if (y == 1) else 2 if (y == -1) else 1
    # also valid: x = (class1 if y == 1 else class2)(arg1, arg2)

    Functions
    def FUN(parameters):
        """ docstring """
        # do stuff
        return ...
    Data Types
  • Numbers:
  • int(), long(), float(), and complex()
    Numbers allow the use of math.floor(), math.ceil(), math.round(x[, n])
  • Strings: If lala="omg so cool", then
    lala[0:4] is "omg".
    lala[0:4]*2 is "omgomg".
    lala + " PUMPKIN!" is "omg so cool PUMPKIN!"
    %
    >>> print '%(lang)s has %(n)03d quote types.' % \
    ... {"lang": "Python", "n": 2}
    Python has 002 quote types.
  • Lists[ ]: Very versatile! Unfrozen Tuples.
    IF li = [1, 12.02, "Cheese"]
    li[0:] is [1, 12.02, "Cheese"]
    li[0:2] is [1, 12.02]
    li[1] is 12.02
    li[-1] is "Cheese"
    li.append("b") is [1, 12.03, "Cheese", "b"]
    li.insert(2, "1") is [1, 12.013, "1", "Cheese"]
    li.extend(["1","2"]) is [1, 12.03, "Cheese", "1", "2"]
    [0,9]*2 returns [0,9,0,9]
  • Tuples( ): In short, frozen lists. No .append, .extend, .insert.
  • Dictionaries{ }: UNORDERED
    d={'one':1, 'two':2} #or
    d={}
    d['one'] = 1 ; d['two'] = 2
    THEN
        d['one'] is 1
        d.keys() is ['one', 'two']
        d.values() is [1, 2]

  • Truth Value Testing
    Any object can be tested for truth value. Basically any empty object, None, or False is considered False:
    - None
    - False
    - 0, 0.00, etc.
    - "", [], or ()
    - {}
    - an object with length 0
    Flow Control
  • If (else) statements
  • if a>b:
        print b
    else:
        print a

  • Loops
    for, while
    Control Statements:
        break (terminates the loop)
        continue (skip the remainder and continue to the next iteration)
        pass (used when a statement is required syntactically but you do not want any command or code to execute.)

  • Nested List comprehensions
  • [(i,j) for i in range(3) for j in range(i) ]
    ((i,j) for i in range(4) for j in range(i) )

  • Exception else clause
  • try:
        put_4000000000_volts_through_it(parrot)
    except Voom:
        print "'E's pining!"
    else:
        print "This parrot is no more!"
    finally:
        end_sketch()

    Argument Unpacking
    def some_function(x, y):
    # do some magic

    tuple_foo = (3, 4)
    dict_bar = {'y': 3, 'x': 2}

    some_function(*tuple_foo)
    some_function(**dict_bar)

    Slice Operators
    a = [1,2,3,4,5]
    # iterate over the whole list in 2-increments
    >>> a[::2]
    [1,3,5]

    # reverse a list:
    >>> a[::-1]
    [5,4,3,2,1]

    Chaining Comparison Operators
    >>> x = 5
    >>> 1 < x < 10
    True
    >>> 10 < x < 20
    False
    >>> x < 10 < x*10 < 100
    True
    >>> 5 == x > 4
    True

    Readable, multi-line regular expressions
    >>> pattern = """
    ... ^ # beginning of string
    ... M{0,4} # thousands - 0 to 4 M's
    ... (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
    ... # or 500-800 (D, followed by 0 to 3 C's)
    ... $ # end of string
    ... """
    >>> re.search(pattern, 'M', re.VERBOSE)