序列切片 >>> a = 'abcd' >>> print a[1:3] bc >>> print a[1:] bcd >>> print a[:] abcd >>> print a[:3] abc >>> print a[:-1] abc >>> print a[-2] c 字符串反转 >>> print a[::-1] dcba a b c d 0 1 2 3 -4 -3 -2 -1
流程控制 if a == 1: print 'aaa' else : print 'bbb' if b == 1: print '111' elif b == 2: print '222' else : print '000' while a < 10: print a a += 1 for item in (1, 2, 3): print item d = {'name': 'smallfish', 'age': 20} for k in d: print k, d[k] for k, v in d.items(): print k, v 输出 age 20 name smallfish
函数( 1 ) def hello(name): "hello function, name is param" print "hello", name >>> print hello.__doc__ hello function, name is param >>> hello('smallfish') hello smallfish # 给函数参数加默认值 def hello(name='smallfish'): # 同上代码 >>> hello() hello smallfish >>> hello('chenxiaoyu') hello chenxiaoyu
修饰器( 2 ) 测试函数: def hello(n): sum = 0 for i in range(n): sum += I return sum 我们可以这样调用: a = time_wrapper(hello) print a(100) 这个不稀奇,还可以这样写: @time_wrapper def hello(n): … 同上 >>> hello(1000000) hello 0.265000104904