Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> >>> >>> S = 'spam' >>> len(S) 4 >>> S + 'NI' 'spamNI' >>> S * 8 'spamspamspamspamspamspamspamspam' >>> >>> S[0] 's' >>> S[1] 'p' >>> S[-1] 'm' >>> S[-2] 'a' >>> S[len(S) - 1] 'm' >>> S[I:J] KeyboardInterrupt >>> >>> S 'spam' >>> S[1:3] 'pa' >>> S[1:] 'pam' >>> S[:4] 'spam' >>> >>> S[0:3] 'spa' >>> S[:-1] 'spa' >>> S[:] 'spam' >>> S[I:J:K] KeyboardInterrupt >>> >>> X ='abcdefghijklmnop' >>> S[::2] 'sa' >>> X[::2] 'acegikmo' >>> X[::-1] 'ponmlkjihgfedcba' >>> >>> S 'spam' >>> S.find('pa') 1 >>> S.upper() 'SPAM' >>> >>> S.replace('pa', 'XYZ') 'sXYZm' >>> >>> line = 'aaa,bbb,ccc\n' >>> >>> line[:-1] 'aaa,bbb,ccc' >>> line.rstrip() 'aaa,bbb,ccc' >>> >>> line 'aaa,bbb,ccc\n' >>> line.split(',') ['aaa', 'bbb', 'ccc\n'] >>> >>> line.rstrip().split(',') ['aaa', 'bbb', 'ccc'] >>> >>> line 'aaa,bbb,ccc\n' >>> cols = line.rstrip().split(',') >>> cols ['aaa', 'bbb', 'ccc'] >>> '++'.join(cols) 'aaa++bbb++ccc' >>> >>> line 'aaa,bbb,ccc\n' >>> line.replace(',', '++') 'aaa++bbb++ccc\n' >>> >>> line 'aaa,bbb,ccc\n' >>> >>> line + 'xxxxx' 'aaa,bbb,ccc\nxxxxx' >>> >>> line 'aaa,bbb,ccc\n' >>> >>> line = line + 'xxxxx' >>> line 'aaa,bbb,ccc\nxxxxx' >>> >>> line[0] = 'x' Traceback (most recent call last): File "", line 1, in line[0] = 'x' TypeError: 'str' object does not support item assignment >>> >>> X = 1 >>> X = X + 1 >>> X 2 >>> >>> L = [123, 'abc', 1.23] >>> >>> len(L) 3 >>> L + [3, 4, 5] [123, 'abc', 1.23, 3, 4, 5] >>> L [123, 'abc', 1.23] >>> L * 3 [123, 'abc', 1.23, 123, 'abc', 1.23, 123, 'abc', 1.23] >>> >>> L [123, 'abc', 1.23] >>> L[0] 123 >>> {-1] SyntaxError: invalid syntax >>> L[-1] 1.23 >>> >>> L[1:] ['abc', 1.23] >>> L [123, 'abc', 1.23] >>> >>> L [123, 'abc', 1.23] >>> L.append(99) >>> L [123, 'abc', 1.23, 99] >>> L.extend([5, 6, 7]) >>> L [123, 'abc', 1.23, 99, 5, 6, 7] >>> >>> L.remove(1.23) >>> L [123, 'abc', 99, 5, 6, 7] >>> >>> L.pop() 7 >>> L [123, 'abc', 99, 5, 6] >>> >>> M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> >>> M [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> >>> M[1] [4, 5, 6] >>> M[1][2] 6 >>> col2 = [row[1] for row in M] >>> col2 [2, 5, 8] >>> >>> [x ** 2 for x in [1, 2, 3, 4, 5]] [1, 4, 9, 16, 25] >>> >>> D = {'food':'spam', 'taste':'yum'} >>> D['food'] 'spam' >>> D.keys() ['food', 'taste'] >>> D.values() ['spam', 'yum'] >>> D.items() [('food', 'spam'), ('taste', 'yum')] >>> >>> D = {'f' + 'ood': S} >>> D {'food': 'spam'} >>> S 'spam' >>> D - {'food': [1, 2, 3, 4, 5]} Traceback (most recent call last): File "", line 1, in D - {'food': [1, 2, 3, 4, 5]} TypeError: unsupported operand type(s) for -: 'dict' and 'dict' >>> >>> D = {'food': [1, 2, 3, 4, 5]} >>> D {'food': [1, 2, 3, 4, 5]} >>> >>> bday= (8, 6, 20000 ) >>> >>> >>> bday= (8, 6, 2000) >>> bday (8, 6, 2000) >>> >>> D = {bday: 'Bob'} >>> D {(8, 6, 2000): 'Bob'} >>> >>> D = {} >>> D['name'] = 'Bob' >>> D['age'] = 40 >>> D['job'] = 'dev' >>> D {'job': 'dev', 'age': 40, 'name': 'Bob'} >>> >>> rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr'], 'age': 40.5} >>> >>> rec['name'] {'last': 'Smith', 'first': 'Bob'} >>> rec['name']['last'] 'Smith' >>> >>> rec.job Traceback (most recent call last): File "", line 1, in rec.job AttributeError: 'dict' object has no attribute 'job' >>> rec['job'] ['dev', 'mgr'] >>> rec['job'].append('janitor') >>> >>> >>> rec {'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first': 'Bob'}} >>> >>> rec = 0 >>> >>> T = (1, 2, 3, 4) >>> T + (6, 7, 8) (1, 2, 3, 4, 6, 7, 8) >>> T * 3 (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4) >>> T]-1] SyntaxError: invalid syntax >>> T[-1] 4 >>> T[1:] (2, 3, 4) >>> T (1, 2, 3, 4) >>> >>> T.count(3) 1 >>> T.append(9) Traceback (most recent call last): File "", line 1, in T.append(9) AttributeError: 'tuple' object has no attribute 'append' >>> T[0] = 1 Traceback (most recent call last): File "", line 1, in T[0] = 1 TypeError: 'tuple' object does not support item assignment >>> >>> F = open('data.txt', 'w') >>> F.write('spam\n') >>> F.write('world\n') >>> F.close() >>> >>> F = open('data.txt') >>> bytes = F.read() >>> bytes 'spam\nworld\n' >>> print bytes spam world >>> F = open(r'C:\mydata\data.txt', 'w') KeyboardInterrupt >>> import os >>> >>> >>> F >>> dir(F) ['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] >>> >>> help(F.readline) Help on built-in function readline: readline(...) readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. >>> help(F) Help on file object: class file(object) | file(name[, mode[, buffering]]) -> file object | | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), | writing or appending. The file will be created if it doesn't exist | when opened for writing or appending; it will be truncated when | opened for writing. Add a 'b' to the mode for binary files. | Add a '+' to the mode to allow simultaneous reading and writing. | If the buffering argument is given, 0 means unbuffered, 1 means line | buffered, and larger numbers specify the buffer size. The preferred way | to open a file is with the builtin open() function. | Add a 'U' to mode to open the file for input with universal newline | support. Any line ending in the input file will be seen as a '\n' | in Python. Also, a file so opened gains the attribute 'newlines'; | the value for this attribute is one of None (no newline read yet), | '\r', '\n', '\r\n' or a tuple containing all the newline types seen. | | 'U' cannot be combined with 'w' or '+' mode. | | Methods defined here: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __enter__(...) | __enter__() -> self. | | __exit__(...) | __exit__(*excinfo) -> None. Closes the file. | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __iter__(...) | x.__iter__() <==> iter(x) | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | close(...) | close() -> None or (perhaps) an integer. Close the file. | | Sets data attribute .closed to True. A closed file cannot be used for | further I/O operations. close() may be called more than once without | error. Some kinds of file objects (for example, opened by popen()) | may return an exit status upon closing. | | fileno(...) | fileno() -> integer "file descriptor". | | This is needed for lower-level file interfaces, such os.read(). | | flush(...) | flush() -> None. Flush the internal I/O buffer. | | isatty(...) | isatty() -> true or false. True if the file is connected to a tty device. | | next(...) | x.next() -> the next value, or raise StopIteration | | read(...) | read([size]) -> read at most size bytes, returned as a string. | | If the size argument is negative or omitted, read until EOF is reached. | Notice that when in non-blocking mode, less data than what was requested | may be returned, even if no size parameter was given. | | readinto(...) | readinto() -> Undocumented. Don't use this; it may go away. | | readline(...) | readline([size]) -> next line from the file, as a string. | | Retain newline. A non-negative size argument limits the maximum | number of bytes to return (an incomplete line may be returned then). | Return an empty string at EOF. | | readlines(...) | readlines([size]) -> list of strings, each a line from the file. | | Call readline() repeatedly and return a list of the lines so read. | The optional size argument, if given, is an approximate bound on the | total number of bytes in the lines returned. | | seek(...) | seek(offset[, whence]) -> None. Move to new file position. | | Argument offset is a byte count. Optional argument whence defaults to | 0 (offset from start of file, offset should be >= 0); other values are 1 | (move relative to current position, positive or negative), and 2 (move | relative to end of file, usually negative, although many platforms allow | seeking beyond the end of a file). If the file is opened in text mode, | only offsets returned by tell() are legal. Use of other offsets causes | undefined behavior. | Note that not all file objects are seekable. | | tell(...) | tell() -> current file position, an integer (may be a long integer). | | truncate(...) | truncate([size]) -> None. Truncate the file to at most size bytes. | | Size defaults to the current file position, as returned by tell(). | | write(...) | write(str) -> None. Write string str to file. | | Note that due to buffering, flush() or close() may be needed before | the file on disk reflects the data written. | | writelines(...) | writelines(sequence_of_strings) -> None. Write the strings to the file. | | Note that newlines are not added. The sequence can be any iterable object | producing strings. This is equivalent to calling write() for each string. | | xreadlines(...) | xreadlines() -> returns self. | | For backward compatibility. File objects now include the performance | optimizations previously implemented in the xreadlines module. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | closed | True if the file is closed | | encoding | file encoding | | errors | Unicode error handler | | mode | file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added) | | name | file name | | newlines | end-of-line convention used in this file | | softspace | flag indicating that a space needs to be printed; used by print | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = | T.__new__(S, ...) -> a new object with type S, a subtype of T >>> >>> help(F.readline) Help on built-in function readline: readline(...) readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. >>> import math >>> math.sqrt(1000) 31.622776601683793 >>> dir(math) ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] >>> help(math.sin) Help on built-in function sin in module math: sin(...) sin(x) Return the sine of x (measured in radians). >>> x = 0b10101010 >>> x 170 >>> x = 0o777 >>> x 511 >>> x = 0xFFF >>> x 4095 >>> x = 0777 >>> x 511 >>> bin(170) '0b10101010' >>> oct(511) '0777' >>> hex(4095) '0xfff' >>> >>> int('123') 123 >>> >>> int('170', 2) Traceback (most recent call last): File "", line 1, in int('170', 2) ValueError: invalid literal for int() with base 2: '170' >>> int('1010101010', 2) 682 >>> eval('0b10101010') 170 >>> >>> '23' + 1 Traceback (most recent call last): File "", line 1, in '23' + 1 TypeError: cannot concatenate 'str' and 'int' objects >>> >>> int('23') 23 >>> str(1) '1' >>> int('23') + 1 24 >>> '23' + str(1) '231' >>> >>> >>> X = 'spam' >>> X = 99 >>> X = [1, 2, 3] >>> >>> >>> L = [1, 2, 3] >>> M = L >>> L == M True >>> L is M True >>> >>> L = [1, 2, 3] >>> M = [1, 2, 3] >>> L == M True >>> L is M False >>> >>> X = 24 >>> Y = 24 >>> X == Y True >>> X is Y True >>> >>> import sys >>> sys.getrefcount(1) 725 >>> >>> msg = ''' aaaaaaaaa bbbbb''bbb"""bb cccccccc''' >>> >>> msg '\naaaaaaaaa\nbbbbb\'\'bbb"""bb\ncccccccc' >>> >>> >>> D = {} >>> D['a'] = 1 >>> D {'a': 1} >>> D['b'] Traceback (most recent call last): File "", line 1, in D['b'] KeyError: 'b' >>> >>> D.has_key('a') True >>> D.has_key('b') False >>> >>> if not D.has_key('b'): print 'missing' missing >>> >>> 'b' in D False >>> >>> D = {'a':1, 'b':2, 'c':3} >>> D {'a': 1, 'c': 3, 'b': 2} >>> >>> Ks = D.keys() >>> Ks ['a', 'c', 'b'] >>> Ks.sort() >>> Ks ['a', 'b', 'c'] >>> >>> for key in Ks: print key, '=>', D[key] a => 1 b => 2 c => 3 >>> dir(D) ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] >>> 1, 2, 3 (1, 2, 3) >>> >>> >>> import struct >>> >>> F = open('data.bin', 'wb') >>> data = struct.pack('>i4sh', 8, 'spam', 9) >>> data '\x00\x00\x00\x08spam\x00\t' >>> >>> F.write(data) >>> F.close() >>> >>> F = open('data.bin', 'rb') >>> byte = F.read() >>> byte '\x00\x00\x00\x08spam\x00\t' >>> >>> vals = struct.unpack('>i4sh', byte) >>> vals (8, 'spam', 9) >>> x, y, z = struct.unpack('>i4sh', byte) >>> x 8 >>> y 'spam' >>> z 9 >>> X = None >>> L = [] >>> L[99] = 1 Traceback (most recent call last): File "", line 1, in L[99] = 1 IndexError: list assignment index out of range >>> >>> L = [None] * 100 >>> L [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None] >>> >>> L = [0] * 100 >>> L [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> >>> type(L) >>> >>> >>> S = {1, 2, 3, 4, 5} >>> S set([1, 2, 3, 4, 5]) >>> ================================ RESTART ================================ >>> 1267650600228229401496703205376 spam!spam!spam!spam!spam!spam!spam!spam! C:\pyclass spamNI >>> >>> x = raw_input('enter:') enter:spam >>> x 'spam' >>> x = raw_input('enter:') enter:50 >>> x '50' >>> ================================ RESTART ================================ >>> Age=>50 2500 Age=>30 900 Age=>10 100 Age=>stop bye >>> ================================ RESTART ================================ >>> Age=>spam Traceback (most recent call last): File "C:/pyclass/interact.py", line 4, in print int(inp) ** 2 ValueError: invalid literal for int() with base 10: 'spam' >>> >>> s = '99' >>> s.isdigit() True >>> ================================ RESTART ================================ >>> Age=>50 2500 Age=>2 4 Age=>spam Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad! Age=>3 9 Age=>stop bye >>> eval('99') 99 >>> eval('99.99') 99.99 >>> float('99') 99.0 >>> float('99.99') 99.99 >>> float('99.99E+100') 9.999e+101 >>> ================================ RESTART ================================ >>> Age=>50.5 Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad! Age=> >>> ================================ RESTART ================================ >>> Age=>80 6400.0 Age=>50 2500.0 Age=>50.5 2550.25 Age=>spam Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad! Age=>2 4.0 Age=>stop bye >>> '99'.lower() '99' >>> 'SPAM'.lower() 'spam' >>> >>> >>> X = Y = 0 >>> X = X + 1 >>> X 1 >>> Y 0 >>> >>> X = Y = [] >>> X.append(1) >>> X [1] >>> Y [1] >>> X, Y = [], [] >>> X.append(1) >>> X [1] >>> Y [] >>> >>> L = [1, 2, 3] >>> L.append(4) >>> L [1, 2, 3, 4] >>> >>> L = L.append(5) >>> print L None >>> help(L.insert) Traceback (most recent call last): File "", line 1, in help(L.insert) AttributeError: 'NoneType' object has no attribute 'insert' >>> L = [1, 2, 3] >>> help(L.insert) Help on built-in function insert: insert(...) L.insert(index, object) -- insert object before index >>> L = [1, 2, 3] >>> L.insert(-1, 4) >>> L [1, 2, 4, 3] >>> >>> L = [1, 2, 3, 4, 3] >>> L.index(3) 2 >>> L = [1, 2, 3, 4, 3] >>> L[2:3] = [7, 8,9] >>> L [1, 2, 7, 8, 9, 4, 3] >>> import docstrings >>> >>> docstrings.__doc__ '\nModule documentation\nWords Go Here\n' >>> >>> print docstrings.__doc__ Module documentation Words Go Here >>> print docstrings.square.__doc__ function documentation can we have your liver then? >>> help(docstrings) Help on module docstrings: NAME docstrings FILE c:\pyclass\docstrings.py DESCRIPTION Module documentation Words Go Here FUNCTIONS square(x) function documentation can we have your liver then? DATA spam = 40 >>> >>> ord('s') 115 >>> ord('spam') Traceback (most recent call last): File "", line 1, in ord('spam') TypeError: ord() expected a character, but string of length 4 found >>> >>> for c in 'spam': print c s p a m >>> >>> F = open('script1.py') >>> F.readline() 'print 2 ** 100\n' >>> F.readline() "print 'spam!' * 8\n" >>> F.readline() 'import os\n' >>> F.readline() 'print os.getcwd()\n' >>> F.readline() "x = 'NI'\n" >>> F.readline() "print 'spam' + x\n" >>> F.readline() '' >>> >>> F = open('script1.py') >>> F.next() 'print 2 ** 100\n' >>> F.next() "print 'spam!' * 8\n" >>> F.next() 'import os\n' >>> F.next() 'print os.getcwd()\n' >>> F.next() "x = 'NI'\n" >>> F.next() "print 'spam' + x\n" >>> F.next() Traceback (most recent call last): File "", line 1, in F.next() StopIteration >>> >>> for line in open('script1.py'): print line.upper(), PRINT 2 ** 100 PRINT 'SPAM!' * 8 IMPORT OS PRINT OS.GETCWD() X = 'NI' PRINT 'SPAM' + X >>> >>> lines = open('script1.py').readlines() >>> lines ['print 2 ** 100\n', "print 'spam!' * 8\n", 'import os\n', 'print os.getcwd()\n', "x = 'NI'\n", "print 'spam' + x\n"] >>> >>> for line in open('script1.py').readlines(): print line.upper(), PRINT 2 ** 100 PRINT 'SPAM!' * 8 IMPORT OS PRINT OS.GETCWD() X = 'NI' PRINT 'SPAM' + X >>> >>> for line in open('script1.py'): print line.upper(), PRINT 2 ** 100 PRINT 'SPAM!' * 8 IMPORT OS PRINT OS.GETCWD() X = 'NI' PRINT 'SPAM' + X >>> >>> F = open('script1.py') >>> while True: line = F.readline() if not line: break print line.upper(), PRINT 2 ** 100 PRINT 'SPAM!' * 8 IMPORT OS PRINT OS.GETCWD() X = 'NI' PRINT 'SPAM' + X >>> >>> D Traceback (most recent call last): File "", line 1, in D NameError: name 'D' is not defined >>> D = {'a':1, 'b':2, 'c':3} >>> for key in D: print key, '=', D[key] a = 1 c = 3 b = 2 >>> >>> D.next() Traceback (most recent call last): File "", line 1, in D.next() AttributeError: 'dict' object has no attribute 'next' >>> >>> D {'a': 1, 'c': 3, 'b': 2} >>> >>> I = iter(D) >>> I.next() 'a' >>> I.next() 'c' >>> I.next() 'b' >>> I.next() Traceback (most recent call last): File "", line 1, in I.next() StopIteration >>> >>> >>> >>> L = [1, 2, 3,4, 5] >>> >>> for x in L: x += 10 >>> x 15 >>> L [1, 2, 3, 4, 5] >>> >>> for i in range(len(L)): L[i] += 10 >>> L [11, 12, 13, 14, 15] >>> >>> L [11, 12, 13, 14, 15] >>> >>> M = [x + 10 for x in L] >>> M [21, 22, 23, 24, 25] >>> >>> L = [x + 10 for x in L] >>> L [21, 22, 23, 24, 25] >>> >>> map(ord, 'spam') [115, 112, 97, 109] >>> >>> [ord(c) for c in 'spam'] [115, 112, 97, 109] >>> >>> [x + 10 for x in L] [31, 32, 33, 34, 35] >>> >>> def spam(x): return x + 10 >>> map(spam, L) [31, 32, 33, 34, 35] >>> >>> map((lambda x: x + 10), L) [31, 32, 33, 34, 35] >>> >>> res = [] >>> for x in L: res.append(x + 10) >>> res [31, 32, 33, 34, 35] >>> >>> F = open('script1.py') >>> lines = F.readlines() >>> lines ['print 2 ** 100\n', "print 'spam!' * 8\n", 'import os\n', 'print os.getcwd()\n', "x = 'NI'\n", "print 'spam' + x\n"] >>> >>> lines = [line.rstrip() for line in lines] >>> lines ['print 2 ** 100', "print 'spam!' * 8", 'import os', 'print os.getcwd()', "x = 'NI'", "print 'spam' + x"] >>> >>> lines = [line.rstrip() for line in open('script1.py')] >>> lines ['print 2 ** 100', "print 'spam!' * 8", 'import os', 'print os.getcwd()', "x = 'NI'", "print 'spam' + x"] >>> >>> lines = [line.rstrip() for line in open('script1.py') if line[0] == 'p'] >>> lines ['print 2 ** 100', "print 'spam!' * 8", 'print os.getcwd()', "print 'spam' + x"] >>> >>> [x + y for x in 'abc' for y in 'lmn'] ['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn'] >>> >>> res = [] >>> for x in 'abc': for y in 'lmn': res.append(x + y) >>> res ['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn'] >>> >>> res = [] >>> for line in open('script1.py'): if line[0] == 'p': res.append(line.rstrip()) >>> res ['print 2 ** 100', "print 'spam!' * 8", 'print os.getcwd()', "print 'spam' + x"] >>> >>> >>> >>> import __builtin__ >>> dir(__builtin__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] >>> >>> open = 32 >>> open 32 >>> del open >>> open >>> >>> True = False >>> __builtin__.True = False KeyboardInterrupt >>> >>> >>> >>> >>> >>> >>> def maker(N): def action(X): return X ** N return action >>> F = maker(8) >>> F >>> F(2) 256 >>> F(3) 6561 >>> >>> G = maker(3) >>> G(2) 8 >>> F(2) 256 >>> >>> def(*args): print args SyntaxError: invalid syntax >>> >>> >>> def func(*args): print args >>> func(1, 2, 3) (1, 2, 3) >>> f(1) Traceback (most recent call last): File "", line 1, in f(1) NameError: name 'f' is not defined >>> func(1) (1,) >>> >>> import timer Traceback (most recent call last): File "", line 1, in import timer ImportError: No module named timer >>> import timeit >>> timeit.Timer(stmt="len(str(2**1000000))").timeit(number=1) 1.8728729276637794 >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=100) 0.01753217335123125 >>> timeit.Timer(stmt="for x in range(1000): res.append(x ** 2)").timeit(number=100) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="for x in range(1000): res.append(x ** 2)").timeit(number=100) File "C:\Python27\lib\timeit.py", line 195, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner NameError: global name 'res' is not defined >>> rs = [] >>> res = [] >>> timeit.Timer(stmt="for x in range(1000): res.append(x ** 2)").timeit(number=100) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="for x in range(1000): res.append(x ** 2)").timeit(number=100) File "C:\Python27\lib\timeit.py", line 195, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner NameError: global name 'res' is not defined >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> D = {'a': 1, 'b': 2, 'c': 3} >>> >>> D {'a': 1, 'c': 3, 'b': 2} >>> >>> >>> dict(a=1, b=2, c=3) {'a': 1, 'c': 3, 'b': 2} >>> >>> >>> >>> >>> >>> >>> >>> >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.15091529048504526 >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.08418414597736046 >>> >>> timeit.Timer(stmt="res=[]; for x in range(1000): res.append(x ** 2)").timeit(number=1000) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="res=[]; for x in range(1000): res.append(x ** 2)").timeit(number=1000) File "C:\Python27\lib\timeit.py", line 136, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 6 res=[]; for x in range(1000): res.append(x ** 2) ^ SyntaxError: invalid syntax >>> >>> >>> >>> >>> import timeit >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.09399608343574073 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.15624277617689586 >>> >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.09472426926049593 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.152262189904377 >>> >>> >>> >>> >>> import timeit >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.09895996492969061 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.15285304672488564 >>> >>> timeit.Timer(stmt="{x: x ** 2 for x in range(1000)}").timeit(number=1000) 0.11265327945102399 >>> timeit.Timer(stmt="res={}\nfor x in range(1000): res[x] = x ** 2").timeit(number=1000) 0.1272394768598133 >>> >>> timeit.Timer(stmt="{x: x ** 2 for x in range(1000)}").timeit(number=1000) 0.10845961329869169 >>> timeit.Timer(stmt="res={}\nfor x in range(1000): res[x] = x ** 2").timeit(number=1000) 0.13445340368207326 >>> >>> timeit.Timer(stmt="{x ** 2 for x in range(1000)}").timeit(number=1000) 0.12166470121655948 >>> timeit.Timer(stmt="res=set()\nfor x in range(1000): res.add(x ** 2)").timeit(number=1000) 0.19810906268776307 >>> >>> >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.08841202220128253 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.15160780009182417 >>> timeit.Timer(stmt="x = 0\nwhile x < 1000: res.append(x ** 2)\n x += 1").timeit(number=1000) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="x = 0\nwhile x < 1000: res.append(x ** 2)\n x += 1").timeit(number=1000) File "C:\Python27\lib\timeit.py", line 136, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 8 x += 1 ^ IndentationError: unexpected indent >>> >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.10071103191739894 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.14649339427933228 >>> timeit.Timer(stmt="x = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="x = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) File "C:\Python27\lib\timeit.py", line 195, in timeit timing = self.inner(it, self.timer) File "", line 8, in inner NameError: global name 'res' is not defined >>> >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.08909182521028924 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.15320834276144524 >>> timeit.Timer(stmt="res=[]\nx = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) 0.19559217879532298 >>> timeit.Timer(stmt="map((lambda x: x ** 2), range(1000)").timeit(number=1000) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="map((lambda x: x ** 2), range(1000)").timeit(number=1000) File "C:\Python27\lib\timeit.py", line 136, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 7 _t1 = _timer() ^ SyntaxError: invalid syntax >>> timeit.Timer(stmt="map((lambda x: x ** 2), range(1000))").timeit(number=1000) 0.18752300016467416 >>> >>> >>> >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.08656272343478122 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.15111322018901774 >>> timeit.Timer(stmt="map((lambda x: x ** 2), range(1000))").timeit(number=1000) 0.1775248621697756 >>> timeit.Timer(stmt="res=[]\nx = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) 0.19573488366859237 >>> ^ SyntaxError: invalid syntax >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> import sys >>> sys.version '2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)]' >>> >>> import timeit >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.08896427051149658 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.14947358029439783 >>> timeit.Timer(stmt="map((lambda x: x ** 2), range(1000))").timeit(number=1000) 0.20180130692233433 >>> timeit.Timer(stmt="x = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="x = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) File "C:\Python27\lib\timeit.py", line 195, in timeit timing = self.inner(it, self.timer) File "", line 8, in inner NameError: global name 'res' is not defined >>> >>> >>> >>> import sys >>> sys.version '2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)]' >>> >>> import timeit >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.10634591954476491 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.15158531918768858 >>> timeit.Timer(stmt="res=[]\nx = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) 0.19493632283774787 >>> >>> >>> timeit.Timer(stmt="{x: x ** 2 for x in range(1000)}").timeit(number=1000) 0.10709902985126973 >>> timeit.Timer(stmt="res={}\nfor x in range(1000): res[x] = x ** 2").timeit(number=1000) 0.1035978733061711 >>> >>> timeit.Timer(stmt="{x ** 2 for x in range(1000)}").timeit(number=1000) 0.15399664057076734 >>> timeit.Timer(stmt="res=set()\nfor x in range(1000): res.add(x ** 2)").timeit(number=1000) 0.18738811473667738 >>> >>> timeit.Timer(stmt="map((lambda x: x ** 2), range(1000))").timeit(number=1000) 0.18699323275905044 >>> >>> >>> >>> >>> >>> import timeit >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.08002566732875493 >>> timeit.Timer(stmt="map((lambda x: x ** 2), range(1000)").timeit(number=1000) Traceback (most recent call last): File "", line 1, in timeit.Timer(stmt="map((lambda x: x ** 2), range(1000)").timeit(number=1000) File "C:\Python27\lib\timeit.py", line 136, in __init__ code = compile(src, dummy_src_name, "exec") File "", line 7 _t1 = _timer() ^ SyntaxError: invalid syntax >>> timeit.Timer(stmt="[x ** 2 for x in range(1000)]").timeit(number=1000) 0.10177887488953274 >>> timeit.Timer(stmt="map((lambda x: x ** 2), range(1000))").timeit(number=1000) 0.19035559415306125 >>> timeit.Timer(stmt="res=[]\nfor x in range(1000): res.append(x ** 2)").timeit(number=1000) 0.1538739730258385 >>> timeit.Timer(stmt="res=[]\nx = 0\nwhile x < 1000:\n res.append(x ** 2)\n x += 1").timeit(number=1000) 0.19909675634744417 >>> >>> >>> >>> fname = 'script1.py' >>> >>> len(open(fname).read()) 87 >>> len(open(fname).readlines()) 6 >>> >>> tot = 0 >>> for line in open(fname): tot += 1 >>> tot 6 >>> >>> tot = 0 >>> for line in open(fname): tot += line(line) Traceback (most recent call last): File "", line 1, in for line in open(fname): tot += line(line) TypeError: 'str' object is not callable >>> for line in open(fname): tot += len(line) >>> tot 87 >>> >>> ================================ RESTART ================================ >>> Bob Smith Sue Jones dev >>> name = 'Bob Smith' >>> name.split() ['Bob', 'Smith'] >>> name.split()[-1] 'Smith' >>> ================================ RESTART ================================ >>> Bob Smith Sue Jones dev Traceback (most recent call last): File "C:/pyclass/person.py", line 11, in print bob.split()[-1] AttributeError: Person instance has no attribute 'split' >>> ================================ RESTART ================================ >>> Bob Smith Sue Jones dev Smith 55000.0 >>> ================================ RESTART ================================ >>> Bob Smith Sue Jones dev Smith Jones 55000.0 >>> import person >>> help(person) Help on module person: NAME person FILE c:\pyclass\person.py CLASSES Person class Person | stuff about people | | Methods defined here: | | __init__(self, name, job=None, pay=0) | | giveRaise(self, percent) | percent should be 0..1 | | lastName(self) >>> help(person.Person) Help on class Person in module person: class Person | stuff about people | | Methods defined here: | | __init__(self, name, job=None, pay=0) | | giveRaise(self, percent) | percent should be 0..1 | | lastName(self) >>> help(person.Person.giveRaise) Help on method giveRaise in module person: giveRaise(self, percent) unbound person.Person method percent should be 0..1 >>> ================================ RESTART ================================ >>> Bob Smith Sue Jones dev Smith Jones 55000.0 >>> ================================ RESTART ================================ >>> Bob Smith Sue Jones dev Smith Jones <__main__.Person instance at 0x00000000027466C8> >>> ================================ RESTART ================================ >>> [Peron: Bob Smith, 0] [Peron: Sue Jones, 50000] Smith Jones [Peron: Sue Jones, 55000.0] >>> ================================ RESTART ================================ >>> [Peron: Bob Smith, 0] [Peron: Sue Jones, 50000] Smith Jones [Peron: Sue Jones, 55000.0] [Peron: Tim Jones, 40000] >>> ================================ RESTART ================================ >>> [Peron: Bob Smith, 0] [Peron: Sue Jones, 50000] Smith Jones [Peron: Sue Jones, 55000.0] [Peron: Tim Jones, 48000.0] >>> ================================ RESTART ================================ >>> [Peron: Bob Smith, 0] [Peron: Sue Jones, 50000] Smith Jones [Peron: Sue Jones, 55000.0] [Peron: Tim Jones, 48000.0] >>> ================================ RESTART ================================ >>> [Peron: Bob Smith, 0, None] [Peron: Sue Jones, 50000, dev] Smith Jones [Peron: Sue Jones, 55000.0, dev] [Peron: Tim Jones, 48000.0, mgr] >>> ================================ RESTART ================================ >>> >>> import glob >>> glob.glob('oracle*') ['oracledb'] >>> >>> import shelve >>> db = shelve.open('oracledb') >>> len(db) 3 >>> db.keys() ['tim', 'bob', 'sue'] >>> >>> t = db['bob'] >>> print t [Peron: Bob Smith, 0, None] >>> >>> t.lastName() 'Smith' >>> t.name 'Bob Smith' >>> ================================ RESTART ================================ >>> >>> ================================ RESTART ================================ >>> tim => [Peron: Tim Jones, 40000, mgr] bob => [Peron: Bob Smith, 0, None] sue => [Peron: Sue Jones, 50000, dev] >>> ================================ RESTART ================================ >>> tim => [Peron: Tim Jones, 40000, mgr] bob => [Peron: Bob Smith, 0, None] sue => [Peron: Sue Jones, 55000.0, dev] >>> ================================ RESTART ================================ >>> tim => [Peron: Tim Jones, 40000, mgr] bob => [Peron: Bob Smith, 0, None] sue => [Peron: Sue Jones, 60500.0, dev] >>> ================================ RESTART ================================ >>> tim => [Peron: Tim Jones, 40000, mgr] bob => [Peron: Bob Smith, 0, None] sue => [Peron: Sue Jones, 66550.0, dev] >>> >>> >>> >>> >>> >>> >>> >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! >>> >>>