Python 2.4.2 (#1, Mar 22 2006, 18:15:19) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 1 + 2 3 >>> 1 <= 1 True >>> 1 < 1 False >>> True or False True >>> True and False False >>> not True False >>> 'a' + 'b' 'ab' >>> 'hello world'[1] 'e' >>> 'hello world'[1:5] 'ello' >>> [1,2] + ['a','b'] [1, 2, 'a', 'b'] >>> ['a','b','c','d'][2] 'c' >>> ['a','b','c','d'][2:4] ['c', 'd'] >>> [x * x for x in [1,2,3]] [1, 4, 9] >>> [x for x in [1,-1,2,-2,3,-3] if x >= 0] [1, 2, 3] >>> ('a','b') ('a', 'b') >>> ('a', 'b', 'c') ('a', 'b', 'c') >>> ('a','b')[0] 'a' >>> ('a','b')[1] 'b' >>> set([1,2]) | set([2,3]) set([1, 2, 3]) >>> set([1,2]) - set([2,3]) set([1]) >>> set([1,2]) & set([2,3]) set([2]) >>> list(set([1,2,3,1,2,3])) [1, 2, 3] >>> {'jeremy':32, 'jack':57, 'katie':29} {'jeremy': 32, 'jack': 57, 'katie': 29} >>> {'jeremy':32, 'jack':57, 'katie':29}['jack'] 57 >>> x = 3 >>> x 3 >>> y Traceback (most recent call last): File "", line 1, in ? NameError: name 'y' is not defined >>> x = x + 2 >>> x 5 >>> y = 3 >>> (x, y) = (y, x) >>> x 3 >>> y 5 >>> if 1 < 2: ... print 'hello' ... else: ... print 'world' ... hello >>> if x < 5: ... print 'less' ... elif x == 5: ... print 'equal' ... else: ... print 'greater' ... equal >>> for i in [3,5,1,4,8]: ... print i * i ... 9 25 1 16 64 >>> k = 0 >>> while k != 10: ... print k ... k = k + 1 ... 0 1 2 3 4 5 6 7 8 9 >>> def square(x): ... return x * x ... >>> square(3) 9 >>> def factorial(n): ... if n == 1: ... return 1 ... else: ... return n * factorial(n - 1) ... >>> factorial(5) 120 >>> (lambda x: x * x)(3) 9 >>> map(lambda x: x * x, [1,2,3,4]) [1, 4, 9, 16] >>> n = 3 >>> map(lambda x: x + n, [1,2,3,4]) [4, 5, 6, 7] >>> def f(): ... n = 4 ... return n ... >>> f() 4 >>> n 3 >>> reduce(lambda x, subtotal: x + subtotal, [1,2,3,4,5], 0) 15 >>> ', '.join(['tom','rick','harry']) 'tom, rick, harry' >>> class Point: ... def __init__(self, x, y): ... self.x = x ... self.y = y ... def distance(self, other): ... return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5 ... >>> p = Point(3,2) >>> p.x 3 >>> p.y 2 >>> p00 = Point(0,0) >>> p11 = Point(1,1) >>> p00.distance(p11) 1.4142135623730951 >>> class ColorPoint(Point): ... def __init__(self, x, y, color): ... Point.__init__(self, x, y) ... self.color = color >>> cp = ColorPoint(2,3,'red') >>> cp.color 'red' >>> cp.x 2 >>> cp.distance(ColorPoint(4,5,'blue')) 2.8284271247461903 >>> isinstance(cp, ColorPoint) True >>> isinstance(cp, Point) True >>> import compiler >>> ast = compiler.parse('1 + 2') >>> ast Module(None, Stmt([Discard(Add((Const(1), Const(2))))])) >>> from compiler.ast import * >>> Const(1) Const(1)