Python基础测试与笔记

1  起始函数

if __name__ == ‘__main__‘:

2  判空

if x:     if not x:

3  迭代判断

Contains:        
    if x in items:   
Iteration:        
    for x in items:

4  交换值,不使用中间变量

a, b = b, a

5  追加字符串   可list列表

‘‘.join(some_strings)

6  异常处理,注意需要捕获的多项异常

try: v. if ...:     except:
raise TypeError(‘bad operand type‘)

7  枚举

for i, item in enumerate(items):

8  表达式判断   类lambda

[i * 3 for i in data if i > 10]

9     包装变量使之成为dictory

d = dict(zip(keys, values))

10  判断输入变量是否想要的类型

isinstance(x,(int,float))
isinstance(‘abc‘, Iterable)

11  默认参数  

def power(x,n=2)

    可变参数(参数引用类型)

def add_end(L=None):  
    if L is None:
    L = []
    L.append(‘END‘)
    return L

   py元组参数(可变参数)

def add_end(*L)

   py键值对参数(关键字参数)

def add_end(**L)

   参数定义的顺序必须是:必选参数、默认参数、可变参数和关键字参数
12  脚本传参    

from sys import argv     ->   argv[0]

13  类型转换    

int(123)   int(‘123’)   str(123)   unicode(123)  float(’12.3’)

14  P3上基本数据类型

Boolean   Numbers  Strings,  Bytes , Bytes Array  , Lists , Tuples ,Sets , Dicts

     其他引用类型

Modual  Function   Class   Method   File   Complied Code

15  string模板

from string import Template
s = Template(‘$z , this is template , is so good , $z‘)
print s.substitute(z=‘abc‘)

16  格式化输出     %d   %x  %f   %i   %s   %r      

print(’name:%s,age:%d’ % (‘king’,123))

17  p3接受用户输入        

s =  input(‘enter you option’)

     p2    

s = raw_input(‘enter you option‘)

18 列表产生   range   xrange(高效)

19 迭代dict    

for value in d.itervalues()   #value 
for k, v in d.iteritems()    #key,value
for i, value in enumerate([‘A‘, ‘B‘, ‘C‘]):   #index,value

20 列表式(完全生成)          

[x * x for x in range(1, 11) if x % 2 == 0]
[m + n for m in ‘ABC‘ for n in ‘XYZ’]

    生成器(调用生成)

(x * x for x in range(10))   
#需要next()调用   
#控制逻辑   yield

21 lambda(函数编程)

lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]

22 装饰器(函数包装,非函数思想中的AOP)

def log(func):
    def wrapper(*args, **kw):
        print ‘call %s():‘ % func.__name__
        print args[0]
        return func(*args, **kw)
    return wrapper
@log
def now(mystr=""):
    print(‘2013-12-25‘)
now(‘aa’)

23 . 偏函数(对复杂函数功能的新定义)

考题:

递归尾优化(看懂如下的示例,证明Py基础阶段完成)

import sys
class TailRecurseException:
  def __init__(self, args, kwargs):
    self.args = args
    self.kwargs = kwargs
def tail_call_optimized(g):
  """
  This function decorates a function with tail call
  optimization. It does this by throwing an exception
  if it is it‘s own grandparent, and catching such
  exceptions to fake the tail call optimization.
  This function fails if the decorated
  function recurses in a non-tail context.
  “""
  def func(*args, **kwargs):
    f = sys._getframe()
    if f.f_back and f.f_back.f_back         and f.f_back.f_back.f_code == f.f_code:
      raise TailRecurseException(args, kwargs)
    else:
      while 1:
        try:
          return g(*args, **kwargs)
        except TailRecurseException, e:
          args = e.args
          kwargs = e.kwargs
  func.__doc__ = g.__doc__
  return func
@tail_call_optimized
def factorial(n, acc=1):
  "calculate a factorial"
  if n == 0:
    return acc
  return factorial(n-1, n*acc)
print factorial(10000)
@tail_call_optimized
def fib(i, current = 0, next = 1):
  if i == 0:
    return current
  else:
    return fib(i - 1, next, current + next)
print fib(10000)


本文出自 “Apprentice” 博客,请务必保留此出处http://apprentice.blog.51cto.com/2214645/1371319

Python基础测试与笔记,布布扣,bubuko.com

Python基础测试与笔记

上一篇:Webkit, Blink, V8, Chromium


下一篇:3、JS函数与DOM事件