cinderweb

Untitled

Oct 14th, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 39.11 KB | None | 0 0
  1. #!/usr/local/bin/python
  2. #########################################################################
  3. # #
  4. # Reserved Words: #
  5. # #
  6. # and elif global or #
  7. # assert else if pass #
  8. # break except import print #
  9. # class exec in raise #
  10. # continue finally is return #
  11. # def for lambda try #
  12. # del from not while #
  13. # #
  14. #########################################################################
  15.  
  16. #########################################################################
  17. # #
  18. # Importing Modules: #
  19. # #
  20. #########################################################################
  21. import sys # access module
  22. from sys import stdout # access module without qualiying name
  23. from sys import * # ditto for all functions/classes in module
  24. from win32com.client import constants # packages are supported - requires __init__.py in dir
  25. exec "import sys" # dynamic imports are possible
  26. __import__("sys") # another form of dynamic import
  27. reload(sys) # reload module code
  28.  
  29. x = sys.argv # access module feature: module.feature
  30. x = argv # access module feature without qualifer - from
  31. x = sys.path # module search path - can be modified - PYTHONPATH
  32. x = sys.__dict__["argv"] # each module has dictionary used for name lookups
  33. x = getattr(sys, "argv") # call built in fetch function
  34. argv = ["/"] # from only assigns name - sys.argv is not changed
  35.  
  36. #########################################################################
  37. # #
  38. # hello: #
  39. # #
  40. #########################################################################
  41. print "hello world" # stdout
  42. print "hello", "world", # comma on end suppresses newline
  43. print ""
  44. x = sys.argv # list of command line arguments
  45. #sys.exit() # exit application
  46.  
  47. #########################################################################
  48. # #
  49. # line spanning: #
  50. # #
  51. #########################################################################
  52. x = "hello" + \
  53. "world" # span several lines- no comments after \
  54. if (0 and # open parenthesis may span lines
  55. 1): pass
  56. x = [ # open list may span lines
  57. "hello",
  58. "world"
  59. ]
  60. x = 10; y = 10 # multiple statements on a line
  61.  
  62. #########################################################################
  63. # #
  64. # Primitive Variable Types: #
  65. # #
  66. #########################################################################
  67. x = 123 # integer
  68. x = 123L # long integer
  69. x = 3.14 # double float
  70. x = 3+4j # complex
  71. x = "hello" # string
  72. x = [0,1,2] # list
  73. x = (0,1,2) # tuple
  74. x = open('hello.py', 'r') # file
  75.  
  76. x = 077 # octal number
  77. x = 0xFF # hexadecimal number
  78. x = 3.14E-2 # scientific format
  79. x = None # null value
  80.  
  81. X = 1 # python is case sensitive X <> x
  82. x = (1 < 2) # boolean: False = 0 (0, Empty, or None); True = 1 | !0
  83.  
  84. #########################################################################
  85. # #
  86. # Strings: #
  87. # #
  88. #########################################################################
  89. x = "" # empty string
  90. x = 'hello' # strings can use either single or double quote
  91. x = r"hello\n" # raw string - retain backslashes
  92. x = """hello""" # triple quoted strings may span several lines
  93.  
  94. y = `x` # convert to string
  95. y = str(123) # convert to string
  96. x = "hello" * 3 # string repeat
  97. x = "hello" + " world" # string concatenate
  98. y = len(x) # string length
  99. for char in x: y = char # iterate through characters
  100.  
  101. # string slicing
  102. y = x[:2] # left(s, b) - "he"
  103. y = x[:-2] # left(s, len(s)+b) - "hello wor"
  104. y = x[-2:] # right(s, -a) - "ld"
  105. y = x[6] # mid(s, a, 1) - "w"
  106. y = x[2:4] # mid(s, a, b-a) - "ll"
  107. y = x[2:-3] # mid(s, a, len(s)+b-a) - "llo wo"
  108. y = x[-4:-2] # mid(s, len(s)-a, -a-b) - "or"
  109.  
  110. # string backslash characters
  111. x = "\\" # backslash
  112. x = "\'" # single quote
  113. x = "\"" # double quote
  114. x = "\a" # bell
  115. x = "\b" # backspace
  116. x = "\e" # escape
  117. x = "\000" # null that does not end string
  118. x = "\n" # newline
  119. x = "\v" # vertical tab
  120. x = "\t" # tab
  121. x = "\r" # carriage return
  122. x = "\f" # formfeed
  123. x = "\077" # octal character
  124. x = "\x7F" # hex character
  125. x = "\z" # any other chars - the slash & char is retained (\z)
  126.  
  127. # string formatting
  128. x = "hello %s" % "world" # %s = string
  129. x = "hello %c" % 0x77 # %c = character
  130. x = "hello %d" % 123 # %d = decimal int
  131. x = "hello %i" % 123 # %i = integer
  132. x = "hello %u" % 123 # %u = unsigned integer
  133. x = "hello %o" % 077 # %o = octal integer (w/o leadin 0)
  134. x = "hello %x" % 0xFF # %x = hex integer lowercase (w/o leadin 0x)
  135. x = "hello %X" % 0xFF # %X = hex integer uppercase (w/o leadin 0x)
  136. x = "hello %e" % 1.23 # %e = floating point (1.230000e+000)
  137. x = "hello %E" % 1.23 # %E = floating point (1.230000E+000)
  138. x = "hello %f" % 1.23 # %f = floating point (1.230000)
  139. x = "hello %g" % 1.23 # %g = floating point (1.23)
  140. x = "hello %G" % 1.23 # %G = floating point (1.23)
  141. x = "hello %s%%" % "world" # %% = literal percent character
  142.  
  143. #########################################################################
  144. # #
  145. # Lists: #
  146. # #
  147. #########################################################################
  148. x = [] # empty list
  149. x = [0, 1, 2, "abc"] # four item list: indexed x[0]..x[3]
  150. x = [0, 1, 2, 3, [1, 2]] # nested sublists
  151. y = len(x) # list length
  152. y = x[0] # indexed item
  153. y = x[4][0] # indexed sublist
  154. x = [0, 1] * 2 # repeat
  155. x = [0, 1, 2] + [3, 4] # concatenation
  156. x = range(5) # make list over range
  157. x = range(0, 5) # make list over range with start index
  158. x = range(0, 5, 1) # make list over range with start index and increment
  159. for item in x: y = item # iterate through list
  160. b = 3 in x # test list membership
  161.  
  162. # list slicing
  163. y = x[:2] # left(L, n) - [0, 1]
  164. y = x[:-2] # left(L, len(L)+b) - [0, 1, 2]
  165. y = x[-2:] # right(L, -a) - [3, 4]
  166. y = x[2:4] # mid(L, a, b-a) - [2, 3]
  167. y = x[1:-3] # mid(L, a, len(L)+b-a) - [1]
  168. y = x[-4:-2] # mid(L, len(L)-a, -a-b) - [1, 2]
  169.  
  170. # methods
  171. x.append(5) # grow list: x[len(x):] = [a]
  172. x.extend([7,8]) # grow list: x[len(x):] = L
  173. x.insert(0, 9) # insert into list
  174. x.remove(9) # remove first item in list with value
  175. y = x.pop() # remove last item from list and return value
  176. y = x.pop(1) # remove indexed item from list and return value
  177. x.reverse() # reverse list
  178. x.sort() # sort list
  179. y = x.index(3) # search list and return index if value found
  180. y = x.count(3) # search list and return number of instances found
  181.  
  182. del x[3] # delete item from list (can also del a slice)
  183. x[1:2] = [] # delete slice
  184.  
  185. x[1] = 'a' # replace item
  186. x[1:2] = ['a', 'b', 'c'] # replace slice
  187.  
  188. x = [0, 1, 2, 3]
  189. y = map(lambda a: a*a, x) # apply function to each item in list
  190. y = filter(lambda a: a>1, x) # return list of items that meet condition
  191. y = reduce(lambda a,b: a+b, x) # return value by applying iteration (sum list)
  192.  
  193. #########################################################################
  194. # #
  195. # Tuples: #
  196. # #
  197. #########################################################################
  198. x = () # empty tuple
  199. x = (0,) # one item tuple
  200. x = (0, 1, 2, "abc") # four item tuple: indexed x[0]..x[3]
  201. x = 0, 1, 2, "abc" # parenthesis are optional
  202. x = (0, 1, 2, 3, (1, 2)) # nested subtuples
  203. y = x[0] # indexed item
  204. y = x[4][0] # indexed subtuple
  205. x = (0, 1) * 2 # repeat
  206. x = (0, 1, 2) + (3, 4) # concatenation
  207. for item in x: y = item # iterate through tuple
  208. b = 3 in x # test tuple membership
  209.  
  210. # tuple slicing
  211. y = x[:2] # left(L, n) - [0, 1]
  212. y = x[:-2] # left(L, len(L)+b) - [0, 1, 2]
  213. y = x[-2:] # right(L, -a) - [3, 4]
  214. y = x[2:4] # mid(L, a, b-a) - [2, 3]
  215. y = x[1:-3] # mid(L, a, len(L)+b-a) - [1]
  216. y = x[-4:-2] # mid(L, len(L)-a, -a-b) - [1, 2]
  217.  
  218. #########################################################################
  219. # #
  220. # Dictionaries: #
  221. # #
  222. #########################################################################
  223. x = {} # empty dictionary
  224. x = {"a": 10, "b": 20} # two item dictionary
  225. x = {"a": 1, "b": {"c": 2, "d": 3}} # nested dictionary
  226. y = x["a"] # indexing by key
  227. y = x["b"]["c"] # indexed subdictionary
  228. x["e"] = 4 # add an entry
  229. x["e"] = 5 # change an entry
  230. del x["e"] # delete an entry
  231. y = len(x) # number of items
  232. y = x.has_key("a") # test if has key
  233. y = x.get("a") # indexing by key
  234. y = x.get("a", "z") # if key not found then return second arg
  235. for item in x.keys(): y = item # iterate over keys
  236. for item in x.values(): y = item # iterate over values
  237. for key, val in x.items(): y = key # iterate over copy of (key, value) pairs
  238. y = x.copy() # shallow copy
  239. x.update(y) # update dictionary with another dictionary's values
  240. x.clear() # remove all items
  241.  
  242. #########################################################################
  243. # #
  244. # Files: #
  245. # #
  246. #########################################################################
  247. x = open("test.txt", "w") # open file for write
  248. x.write("hello\n") # write string
  249. x.writelines(["fred\n", "hank\n"]) # write all strings in list
  250. x.flush() # flush buffer
  251. y = x.fileno() # file handle number
  252. b = x.isatty() # true if tty device
  253. b = x.closed # current state of file object
  254. y = x.name # file name
  255. b = x.softspace # boolean to indicate whether print requires space
  256. x.close() # close file
  257.  
  258. x = open("test.txt", "r") # open file for input
  259.  
  260. while 1: # iterate through the file one line at a time
  261. y = x.readline()
  262. if (not y): break
  263. for each in x.readlines(): y = each # iterate through the file
  264.  
  265. y = x.read() # read entire file into a string
  266. y = x.read(5) # read n characters
  267. y = x.readline() # read next line
  268. y = x.readlines() # read file into list of strings
  269. y = x.seek(0) # seek to the specified byte
  270. y = x.tell() # tell current file position
  271. x.close()
  272.  
  273. import pickle
  274. x = open("test.txt", "w")
  275. pickle.dump([0, 1, 2], x) # save an object off to file - serialize
  276. x.close
  277.  
  278. x = open("test.txt", "r")
  279. y = pickle.load(x) # restore an object from file
  280. x.close
  281.  
  282. #########################################################################
  283. # #
  284. # Operators: #
  285. # #
  286. # `` convert to string & bitwise and #
  287. # () tuple ^ bitwise exclusive or #
  288. # [] list | bitwise or #
  289. # {} dictionary < less than #
  290. # [x] indexing <= less than or equal #
  291. # [x:y] slicing > greater than #
  292. # m.f qualification >= greater than or equal #
  293. # f() function call == equal #
  294. # - unary negation <> not equal #
  295. # + unary positive != not equal #
  296. # ~ bitwise compliment is identity #
  297. # ** exponentiation is not identity not #
  298. # * multiply | repeat in sequence membership #
  299. # / divide not in sequence non-membership #
  300. # % remainder (modulo) not logical not #
  301. # + add and logical and #
  302. # - subtract or logical or #
  303. # << shift left lambda anonymous function #
  304. # >> shift right #
  305. # #
  306. #########################################################################
  307. x = 0 # assignment
  308. x = y = 0 # compound assignment
  309. [x, y, z] = [0, 1, 2] # positional list assignment: x=0, y=1, z=2
  310. x, y, z = (0, 1, 2) # positional tuple assignment: x=0, y=1, z=2
  311. b = (0 < x < 2) # range test
  312.  
  313. x = -5 # unary minus
  314. x = +5 # unary plus
  315. x = ~0x7f # bitwise compliment
  316. x = 2 ** 8 # power operator
  317. x = 5 / 2 # divide - if both int's then div function
  318. x = 5 % 2 # remainder modulo
  319. x = 5 + 2 # add
  320. x = 5 - 2 # subtract
  321. x = 0x0f << 2 # shift left
  322. x = 0x3c >> 2 # shift right
  323. x = 0x0f & 0x8f # bitwise and
  324. x = 0x0f | 0x80 # bitwise or
  325. x = 0x0f ^ 0x80 # bitwise xor
  326.  
  327. x = [0, 1, 2]
  328. y = [0, 1, 2]
  329.  
  330. b = (x == y) # equal
  331. b = (x != y) # not equal - preferred
  332. b = (x <> y) # not equal
  333. b = (x < y) # less than
  334. b = (x <= y) # less than or equal
  335. b = (x > y) # greater than
  336. b = (x >= y) # greater than or equal
  337.  
  338. b = (x is y) # identity reference
  339. b = (x is not y) # different reference
  340. b = (1 in x) # membership
  341. b = (1 not in x) # not member
  342. b = not 0 # logical not
  343. b = 0 and 1 # logical and
  344. b = 0 or 1 # logical or
  345.  
  346. x = (1+2j).conjugate() # conjugate of complex number
  347.  
  348. #########################################################################
  349. # #
  350. # Flow Control: #
  351. # #
  352. #########################################################################
  353. x = 10
  354. y = 10
  355. b = 1
  356.  
  357. if (b): # if then else
  358. y = 1
  359. elif (x == 10):
  360. y = 2
  361. else:
  362. y = 3
  363.  
  364. while (x != 0): # while loop
  365. x = x - 1
  366. pass # empty placeholder
  367. if (b): continue # continue with next loop
  368. break; # break out of loop
  369. else: # run if didn't exit loop with break
  370. x = x + 1
  371.  
  372. for x in range(4): # for loop
  373. y = y + 1
  374. pass
  375. if (b): continue
  376. break;
  377. else: # run if didn't exit loop with break
  378. y = y + 1
  379.  
  380. #########################################################################
  381. # #
  382. # Exceptions and Assertions: #
  383. # #
  384. #########################################################################
  385. class myGeneralError: pass # define class and subclass to use with exceptions
  386. class mySpecificError(myGeneralError): pass
  387.  
  388. try: # try-catch block
  389. raise AttributeError # throw an exception
  390. raise IOError, "bad IO" # with an exception message
  391. raise mySpecificError() # with user defined exception class
  392. except AttributeError: # catch a specific exception
  393. pass
  394. except myGeneralError: # catch user defined exception (subclasses also caught)
  395. pass
  396. except IOError, msg: # catch a specific exception with extra data
  397. pass
  398. except (RuntimeError, StandardError): # catch any of the list of exceptions
  399. pass
  400. except: # catch all exceptions not handled above
  401. pass
  402. else: # run if no exceptions thrown
  403. pass
  404.  
  405. try: # try-finally block - note exception propogates up
  406. x = 1
  407. finally: # always perform this block
  408. pass
  409.  
  410. assert(1<2) # raise AssertionError if condition not met
  411. assert(1<2), "Assertion message" # with message to display
  412.  
  413. #########################################################################
  414. # #
  415. # Functions: #
  416. # #
  417. #########################################################################
  418. def factorial(n): # define a function
  419. if (n == 1):
  420. return (1)
  421. else:
  422. return (n * factorial(n-1))
  423.  
  424. x = factorial(5) # call a function
  425. x = factorial # indirect call to function
  426. y = x(5)
  427.  
  428. def accessglobal():
  429. global glib # assign to var from global scope
  430. glib = 100
  431.  
  432. glib = 0
  433. accessglobal()
  434.  
  435. def outer(a, b):
  436. i = 100
  437. def inner(c=a, d=b): # only access to outer vars is thru default params
  438. i = 101 # var is local to inner scope
  439. inner() # outer scope var not changed
  440.  
  441. x = outer(1, 2)
  442.  
  443.  
  444. def test(a, b, c=0, d=0): # default values for optional parameters
  445. pass # vals eval'd when def parsed - not when function called
  446.  
  447. test(1, 2)
  448. test(1, 2, 3, 4)
  449. test(a=1, b=2) # keyword matched parameters
  450. test(1, d=1, b=2)
  451.  
  452. def posA(a, *b): # match remaining positional chars in tuple
  453. pass
  454.  
  455. posA(1, 2, 3, 4)
  456.  
  457. def posB(a, **b): # match remaining positional chars in dictionary
  458. pass
  459.  
  460. posB(1, b=2, c=3, d=4)
  461.  
  462. x = lambda a: a * a # lambda functions
  463. y = x(2)
  464.  
  465. x = apply(factorial, (5,)) # built-in apply function
  466.  
  467. #########################################################################
  468. # #
  469. # Classes: #
  470. # #
  471. #########################################################################
  472. class Shape:
  473. def __init__(self, x, y):
  474. self.x = x
  475. self.y = y
  476.  
  477. class Drawable:
  478. def draw(self):
  479. pass
  480.  
  481. def getNumInstances(): # class functions not supported - use module function
  482. return Circle.numInstances
  483.  
  484. class Circle(Shape, Drawable):
  485. numInstances = 0 # class attribute (static)
  486.  
  487. def __init__(self, x, y, radius): # constructor
  488. Shape.__init__(self, x, y)
  489. self.radius = radius
  490. Circle.numInstances = Circle.numInstances + 1
  491. def __del__(self): # destructor
  492. pass
  493.  
  494. def draw(self): print "Drawing a", self.__repr__() # normal instance method
  495. def __mangle(self): pass # mangle: _Circle__mangle
  496.  
  497. def __repr__(self): # print X or `X`
  498. return "Circle at:(%d,%d), radius %d" % (self.x, self.y, self.radius)
  499. def __str__(self): return self.__repr__() # convert to string
  500. def __hash__(self): return 0 # 32 bit hash int
  501. def __nonzero__(self): return 1 # truth test
  502. def __cmp__(self, other): return 0 # compare self to other
  503.  
  504. def __getattr__(self, name): return self.__dict__[name] # control attribute access
  505. def __setattr__(self, name, val): self.__dict__[name] = val # set attribute value
  506. def __delattr__(self, name): pass # delete attribute
  507. def __call__(self, *args): return self.__repr__() # function call x()
  508.  
  509. def __len__(self): return 1 # get length
  510. def __getitem__(self, key): pass # get indexed item
  511. def __setitem__(self, key, val): pass # set indexed item
  512. def __delitem__(self, key): pass # delete indexed item
  513.  
  514. def __getslice__(self, i, j): pass # get indexed slice
  515. def __setslice__(self, i, j, val): pass # set indexed slice
  516. def __delslice__(self, i, j): pass # delete indexed slice
  517.  
  518. def __add__(self, other): pass # + operator
  519. def __sub__(self, other): pass # - operator
  520. def __mul__(self, other): pass # * operator
  521. def __div__(self, other): pass # / operator
  522. def __mod__(self, other): pass # % operator
  523. def __divmod__(self, other): return (1, 2) # divmod()
  524. def __pow__(self, other, *modulo): pass # pow()
  525. def __lshift__(self, other): pass # << operator
  526. def __rshift__(self, other): pass # >> operator
  527. def __and__(self, other): pass # & operator
  528. def __or__(self, other): pass # | operator
  529. def __xor__(self, other): pass # ^ operator
  530.  
  531. def __radd__(self, other): pass # + operator - reversed
  532. def __rsub__(self, other): pass # - operator - reversed
  533. def __rmul__(self, other): pass # * operator - reversed
  534. def __rdiv__(self, other): pass # / operator - reversed
  535. def __rmod__(self, other): pass # % operator - reversed
  536. def __rdivmod__(self, other): return (1, 2) # divmod() - reversed
  537. def __rpow__(self, other): pass # pow() - reversed
  538. def __rlshift__(self, other): pass # << operator - reversed
  539. def __rrshift__(self, other): pass # >> operator - reversed
  540. def __rand__(self, other): pass # & operator - reversed
  541. def __ror__(self, other): pass # | operator - reversed
  542. def __rxor__(self, other): pass # ^ operator - reversed
  543.  
  544. def __pos__(self): pass # + operator - unary plus
  545. def __neg__(self): pass # - operator - unary minus
  546. def __abs__(self): pass # abs()
  547. def __invert__(self): pass # invert function
  548.  
  549. def __complex__(self): pass # complex()
  550. def __int__(self): pass # int()
  551. def __long__(self): pass # long()
  552. def __float__(self): pass # float()
  553. def __oct__(self): pass # oct()
  554. def __hex__(self): pass # hex()
  555. def __coerce__(self, other): pass # coerce for mixed mode
  556.  
  557. scribble = Circle(15, 25, 8) # allocate object
  558. scribble.draw() # method call
  559. Circle.draw(scribble) # alternative form of method call
  560. x = getNumInstances() # static function emulation
  561. x = scribble.__dict__ # dictionary used to store object attributes
  562. x = scribble.__class__ # class which object belongs to
  563. del scribble # manually delete object
  564.  
  565. #########################################################################
  566. # #
  567. # Documentation strings: #
  568. # #
  569. #########################################################################
  570. def docMe():
  571. "this is documentation for a function"
  572. pass
  573.  
  574. class docYou:
  575. "this is documentation for a class"
  576.  
  577. def methYou(self):
  578. "this is a documentation for a method"
  579. pass
  580.  
  581. x = docMe.__doc__ # retrieve documentation string
  582. x = docYou.__doc__
  583. x = docYou.methYou.__doc__
  584.  
  585. #########################################################################
  586. # #
  587. # __builtins__ #
  588. # #
  589. # __debug__ divmod isinstance raw_input #
  590. # __doc__ eval issubclass reduce #
  591. # __import__ execfile len reload #
  592. # __name__ exit list repr #
  593. # abs filter locals round #
  594. # apply float long setattr #
  595. # buffer getattr map slice #
  596. # callable globals max str #
  597. # chr hasattr min tuple #
  598. # cmp hash oct type #
  599. # coerce hex open vars #
  600. # compile id ord xrange #
  601. # complex input pow #
  602. # delattr int quit #
  603. # dir intern range #
  604. # #
  605. # ArithmeticError IndexError RuntimeError #
  606. # AssertionError KeyError StandardError #
  607. # AttributeError KeyboardInterrupt SyntaxError #
  608. # EOFError LookupError SystemError #
  609. # Ellipsis MemoryError SystemExit #
  610. # EnvironmentError NameError TypeError #
  611. # Exception None ValueError #
  612. # FloatingPointError NotImplementedError ZeroDivisionError #
  613. # IOError OSError #
  614. # ImportError OverflowError #
  615. # #
  616. #########################################################################
  617. if (__debug__): pass # flag for debug mode
  618. x = __doc__ # get documentation string
  619. __import__("sys") # built in import function
  620. if (__name__ == "__main__"): pass # check if this is the top level module
  621. x = abs(-5) # abs value
  622. x = apply(factorial, (5,)) # apply function
  623. x = buffer("hello") # create reference to buffer object
  624. b = callable("hello") # flag whether object is callable x()
  625. x = chr(0x2A) # convert ascii int to character
  626. x = cmp(1, 2) # compare function (-1 0 or 1)
  627. x = coerce(1, 2.0) # return tuple with two arguments coerced to common type
  628. #compile("x = 1", "test.pyc", "exec") # compile the string into a code object
  629. x = complex(1, 2) # build complex number: same as (1+2j)
  630. #delattr(Circle, "numInstances") # delete attribute from object
  631. x = dir() # list of items in the dictionary
  632. x = dir(__builtins__) # list of built in objects
  633. (x, y) = divmod(4, 3) # return both div and mod values in a tuple
  634. x = eval("1 + 2") # evaluate string as python code
  635. x = execfile("test.py") # pull in external file
  636. y = filter(lambda a: a>1, [1, 2, 3]) # return list of items that meet condition
  637. x = float(3) # convert to floating point
  638. x = getattr(sys, "argv") # fetch attribute
  639. x = globals() # dictionary with current global symbol table
  640. b = hasattr(Circle, "numInstances") # test if object has attribute
  641. x = hash("abc") # return 32 bit hash value for object
  642. x = hex(0x7f) # convert int to hex string
  643. x = id("abc") # return the identity of the object
  644. #try: x = input(">Prompt") # get input from user prompt
  645. #except: pass
  646. x = int(3.56) # convert to int - truncate
  647. x = intern("abc") # intern a string - for speeding up lookups
  648. b = isinstance(x, Circle) # test if object is instance of class or a subclass
  649. b = issubclass(Circle, Shape) # test if class is a subclass
  650. x = len([1, 2, 3]) # length of sequence
  651. x = list([1, 2, 3]) # convert to or copy list
  652. x = locals() # dictionary with current local symbol table
  653. x = long(3.56) # convert to long - truncate
  654. y = map(lambda a: a*a, [1, 2, 3]) # apply function to each item in list
  655. x = max([1, 2, 3]) # max item value in sequence
  656. x = min([1, 2, 3]) # min item value in sequence
  657. x = oct(077) # convert int to octal string
  658. x = open("test.txt", "r") # open file
  659. x = ord("a") # convert ascii char to int
  660. x = pow(2, 4) # power function
  661. x = range(0, 5, 1) # make list over range with start index and increment
  662. #try: x = raw_input(">Prompt") # get input from user prompt
  663. #except: pass
  664. y = reduce(lambda a,b: a+b, [1, 2, 3]) # return value by applying iteration (sum list)
  665. reload(sys) # reload module code
  666. x = repr("hello") # get string representation of object
  667. x = round(1.5) # round value (2.0)
  668. x = round (123.456, 2) # round to decimal place (123.46)
  669. x = round (123.456, -2) # round to digit (100.0)
  670. setattr(Circle, "numInstances", 2) # set attribute value
  671. x = slice(0, 5, 1) # create a slice attribute in range form
  672. x = str(1.0) # convert to string
  673. x = tuple([1, 2, 3]) # convert to tuple
  674. x = type([1, 2, 3]) # object type
  675. x = vars() # dictionary with current local symbol table
  676. x = vars(Circle) # return local symbol table of object
  677. x = xrange(0, 5, 1) # same as range, but does not create a list
  678.  
  679. x = None # null object
  680.  
  681. try:
  682. raise Exception # root class for all exceptions
  683. raise StandardError # base class for all exceptions except SystemExit
  684. raise ArithmeticError # base class for arithmetic exceptions
  685. raise LookupError # base class for key or index exceptions
  686. raise EnvironmentError # base class for external exceptions
  687.  
  688. raise AssertionError # assert statement fails
  689. raise AttributeError # attribute reference fails
  690. raise EOFError # eof condition without reading any data
  691. raise FloatingPointError # floating point operation fail
  692. raise ImportError # import statement fail
  693. raise IndexError # sequence subscript out of range
  694. raise IOError # io exception
  695. raise KeyError # dictionary key not found
  696. raise KeyboardInterrupt # user hit interrupt key
  697. raise MemoryError # out of memory
  698. raise NameError # local or global name not found
  699. raise NotImplementedError # used for abstract classes
  700. raise OverflowError # overflow exception
  701. raise OSError # os exception
  702. raise RuntimeError # exceptions that don't fit other classes
  703. raise SyntaxError # syntax error encountered
  704. raise SystemError # internal error
  705. raise SystemExit # sys.exit command
  706. raise TypeError # built in applied to inappropriate object
  707. raise ValueError # built in has correct type but bad value
  708. raise ZeroDivisionError # divide by zero error
  709.  
  710. except:
  711. pass
Advertisement
Add Comment
Please, Sign In to add comment