
>>> 123 + 222                            # integer addition
345
>>> 1.5 * 4                              # floating-point multiplication
6.0
>>> 2 ** 100                             # 2 to the power 100
1267650600228229401496703205376L



>>> 3.1415 * 2                           # repr: as code
6.2830000000000004
>>> print 3.1415 * 2                     # str: user-friendly
6.283



>>> import math
>>> math.pi
3.1415926535897931
>>> math.sqrt(85)
9.2195444572928871



>>> import random
>>> random.random()
0.59268735266273953
>>> random.choice([1, 2, 3, 4])
1



>>> S = 'Spam'
>>> len(S)                              # length
4
>>> S[0]                                # the first item in S, indexing by zero-based position
'S'
>>> S[1]                                # the second from the left
'p'



>>> S[-1]                               # the last item from the end in S
'm'
>>> S[-2]                               # the second last from the end
'a'



>>> S[-1]                               # the last item in S
'm'
>>> S[len(S)-1]                         # negative indexing, the hard way
'm'



>>> S                  # a 4-character string
'Spam'
>>> S[1:3]             # slice of S from offsets 1 through 2 (not 3)
'pa'



>>> S[1:]              # everything past the first (1:len(S))
'pam'
>>> S                  # S itself hasnt changed
'Spam'
>>> S[0:3]             # everything but the last 
'Spa'
>>> S[:3]              # same as S[0:3]
'Spa'
>>> S[:-1]             # everything but the last again, but simpler (0:-1)
'Spa'
>>> S[:]               # all of S as a top-level copy (0:len(S))
'Spam'



>>> S
'Spam'
>>> S + 'xyz'                                 # concatenation
'Spamxyz'
>>> S                                         # S is unchanged
'Spam'
>>> S * 8                                     # repitition
'SpamSpamSpamSpamSpamSpamSpamSpam'



>>> S
'Spam'
>>> S[0] = 'z'                             # immutable objects canot be changed
error text omittted
TypeError: 'str' object does not support item assignment

>>> S = 'z' + S[1:]                        # but we can run expression to make new objects
>>> S
'zpam'



>>> S.find('pa')                   # find the offset of a substring
1
>>> S
'Spam'
>>> S.replace('pa', 'XYZ')        # replace occurrences of a substring with another
'SXYZm'
>>> S
'Spam'



>>> line = 'aaa,bbb,ccccc,dd'
>>> line.split(',')                       # split on a delimiter into a list of substrings
['aaa', 'bbb', 'ccccc', 'dd']

>>> S = 'spam'
>>> S.upper()                             # upper and lower case conversions
'SPAM'

>>> S.isalpha()                           # content tests: isalpha, isdigit,
True

>>> line = 'aaa,bbb,ccccc,dd\n'
>>> line = line.rstrip()                  # remove whitespace characters on the right side
>>> line
'aaa,bbb,ccccc,dd'



>>> dir(S)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', 
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 
'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']



>>> help(S.index)
Help on built-in function index:

index(...)
    S.index(sub [,start [,end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.



>>> S = 'A\nB\tC'         # \n is end-of-line, \t is tab
>>> len(S)                # each stands for just one character 
5

>>> ord('\n')             # \n is a byte with binary value 10 in ASCII
10

>>> S = 'A\0B\0C'         # \0, the binary zero byte, does not terminate the string
>>> len(S)
5



>>> msg = """
aaaaaaaaaaaaa
bbb'''bbbbbbbbbb""bbbbbbb'bbbb
cccccccccccccc"""

>>> msg
'\naaaaaaaaaaaaa\nbbb\'\'\'bbbbbbbbbb""bbbbbbb\'bbbb\ncccccccccccccc'



>>> import re
>>> match = re.match('Hello[ \t]*(.*)world', 'Hello    Python world')
>>> match.group(1)
'Python '



>>> match = re.match('/(.*)/(.*)/(.*)', '/usr/home/lumberjack')
>>> match.groups()
('usr', 'home', 'lumberjack')



>>> L = [123, 'spam', 1.23]         # a list of 3 different type objects
>>> len(L)                          # number of items in the list
3



>>> L[0]                            # indexing by position
123

>>> L[:-1]                          # slicing a list returns a new list
[123, 'spam']

>>> L + [4, 5, 6]                   # concatenation makes a new list too
[123, 'spam', 1.23, 4, 5, 6]

>>> L                               # were not changing the original list
[123, 'spam', 1.23]



>>> L.append('NI')                     # growing: add object at end of list
>>> L
[123, 'spam', 1.23, 'NI']

>>> L.pop(2)                           # shrinking: delete an item in the middle        
1.23
>>> L                                  # "del L[2]" deletes from a list too
[123, 'spam', 'NI']



>>> M = ['bb', 'aa', 'cc']
>>> M.sort()
>>> M
['aa', 'bb', 'cc']

>>> M.reverse()
>>> M
['cc', 'bb', 'aa']



>>> L
[123, 'spam', 'NI']

>>> L[99]
error text omitted
IndexError: list index out of range

>>> L[99] = 1
error text omitted
IndexError: list assignment index out of range



>>> M = [[1, 2, 3],              # a 3 x 3 matrix, as nested lists
         [4, 5, 6],
         [7, 8, 9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]



>>> M[1]                         # get row 2
[4, 5, 6]

>>> M[1][2]                      # get row 2, then get item 3 within the row
6



>>> col2 = [row[1] for row in M]               # collect the items in column 2
>>> col2
[2, 5, 8]
 
>>> M                                           # the matrix is unchanged
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 



>>> [row[1] + 1 for row in M]                   # add 1 to each item in column 2
[3, 6, 9]

>>> [row[1] for row in M if row[1] % 2 == 0]    # filter out odd items
[2, 8]



>>> diag = [M[i][i] for i in [0, 1, 2]]         # collect a diagonal from matrix
>>> diag
[1, 5, 9]

>>> doubles = [c * 2 for c in 'spam']           # repeat characters in a string
>>> doubles
['ss', 'pp', 'aa', 'mm']



>>> D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}



>>> D['food']                          # fetch value of key food
'Spam'

>>> D['quantity'] += 1                 # add 1 to quantity value
>>> D
{'food': 'Spam', 'color': 'pink', 'quantity': 5} 



>>> D = {}
>>> D['name'] = 'Bob'                  # create keys by assignment
>>> D['job']  = 'dev'
>>> D['age']  = 40

>>> D
{'age': 40, 'job': 'dev', 'name': 'Bob'}

>>> print D['name']
Bob



>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},
           'job':  ['dev', 'mgr'],
           'age':  40.5}



>>> rec['name']                         # name is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

>>> rec['name']['last']                 # index the nested dictionary
'Smith'

>>> rec['job']                          # job is a nested list
['dev', 'mgr']

>>> rec['job'][-1]                      # index the nested list
'mgr'

>>> rec['job'].append('janitor')        # expane Bobs job description in-place
>>> rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first': 'Bob'}}



>>> rec = 0                  # now the prior objects space is reclaimed



>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'a': 1, 'c': 3, 'b': 2}



>>> Ks = D.keys()                   # unordered keys list
>>> Ks
['a', 'c', 'b']

>>> Ks.sort()                       # sorted keys list
>>> Ks
['a', 'b', 'c']
 
>>> for key in Ks:                  # iterate though sorted keys
	    print key, '=>', D[key]
	
a => 1
b => 2
c => 3



>>> D
{'a': 1, 'c': 3, 'b': 2}

>>> for key in sorted(D):
        print key, '=>', D[key]

	
a => 1
b => 2
c => 3



>>> for c in 'spam':
	    print c.upper()

S
P
A
M



>>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]]
>>> squares
[1, 4, 9, 16, 25]



>>> squares = []
>>> for x in [1, 2, 3, 4, 5]:                 # this is what a list comp does
        squares.append(x ** 2)

>>> squares
[1, 4, 9, 16, 25]



>>> D
{'a': 1, 'c': 3, 'b': 2}

>>> D['e'] = 99                           # assign new keys grows dictionaries
>>> D
{'a': 1, 'c': 3, 'b': 2, 'e': 99}

>>> D['f']                                # referencing one is an error
error text omitted
KeyError: 'f'



>>> D.has_key('f')
False

>>> if not D.has_key('f'):
        print 'missing'
	
missing



>>> T = (1, 2, 3, 4)                 # a 4-item tuple
>>> len(T)                           # length
4

>> T + (5, 6)                        # concatenation
(1, 2, 3, 4, 5, 6)

>>> T[0]                             # indexing, slicing, and more
1



>>> T[0] = 2                          # they are immutable
error text omitted
TypeError: 'tuple' object does not support item assignment



>>> f = open('data.txt', 'w')          # make a new file in output mode
>>> f.write('Hello\n')                 # write strings of bytes to it
>>> f.write('world\n')
>>> f.close()                          # close to flush outout buffers to disk



>>> f = open('data.txt')               # 'r' is the default processing mode
>>> bytes = f.read()                   # read entire file into a string
>>> bytes
'Hello\nworld\n'

>>> print bytes                        # print interprets control characters
Hello
world

>>> bytes.split()                      # file content is always a string 
['Hello', 'world']



>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', 
'__getattribute__', '__hash__', '__init__', '__iter__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 
'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 
'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 
'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

>>> help(file.seek)
try it and see



>>> X = set('spam')
>>> Y = set(['h', 'a', 'm'])                        # make 2 sets out of sequences
>>> X, Y
(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))
 
>>> X & Y                                           # intersection
set(['a', 'm'])

>>> X | Y                                           # union 
set(['a', 'p', 's', 'h', 'm'])

>>> X  Y                                           # difference
set(['p', 's'])



>>> import decimal                              # decimals
>>> d = decimal.Decimal('3.141')
>>> d + 1
Decimal("4.141")

>>> 1 > 2, 1 < 2                                # Booleans
(False, True)
>>> bool('spam')
True

>>> X = None                                    # None placeholder
>>> print X
None
>>> L = [None] * 100                            # initialize a list of 100 Nones
>>> L
[None, None, None, None, None, None, None, None, None, None, None, None, None, 
a list of 100 Nones]

>>> type(L)                                     # types
<type 'list'>
>>> type(type(L))                               # even types are objects
<type 'type'>



>>> if type(L) == type([]):          # type testing, if you must
	    print 'yes'
	
yes
>>> if type(L) == list:              # using the type name
	    print 'yes'
	
yes
>>> if isinstance(L, list):          # object oriented tests
 	    print 'yes'
	
yes



>>> class Worker:
        def __init__(self, name, pay):                # initialize when created
            self.name = name                          # self is the new object 
            self.pay  = pay                           
        def lastName(self):
            return self.name.split()[-1]              # split string on blanks
        def giveRaise(self, percent):
            self.pay *= (1.0 + percent)               # update pay in-place



>>> bob = Worker('Bob Smith', 50000)                  # make two instances
>>> sue = Worker('Sue Jones', 60000)                  # each has name and pay
>>> bob.lastName()                                    # call method: bob is self
'Smith'
>>> sue.lastName()                                    # sue is the self subject
'Jones'
>>> sue.giveRaise(.10)                                # updates sues pay
>>> sue.pay
66000.0




