Python basic learning code-function and functional programming

Source: Internet
Author: User
Python basic learning code-function and functional programming
def func1():    print 'hello world'res = func1()print type(res)def func2():    return ['xyz',10000,-98]atuple = func2()x,y,z = func2()print x,y,zdef func3():    return 'xyz',1000,-98x,y,z = func3()print x,y,zdef func4():    return ['xyz',1000,-98,'xxx']x,y,z,d = func4()alist = x,y,z,dprint alisttrue = lambda :Trueprint true()sum = lambda x,y:x + ysumm = lambda x,y=4:x + yatuplet = lambda *zaz:zazprint atuplet('a',1)adictt = lambda **z:zprint adictt(x=3,y=5)from random import randintdef functest(arg):    return arg % 2allnums = []for eachnum in range(9):    allnums.append(eachnum)print filter(functest,allnums)allnums = []for eachnum in range(9):#    print eachnum    ra = randint(1,99)#    print ra    allnums.append(ra)#print filter(lambda x:x%2,allnums)#print [i for i in allnums if i%2]print [n for n in [randint(1,99) for i in range(9)] if n%2]print map(lambda x:x+2,[i for i in range(9)])print map(lambda x:x**2,[int(i) for i in range(9)])print map(str,[i for i in range(9)])print map(lambda x,y:x+y,[1,2,3],[1,2,3])print map(lambda x,y:(x+y,x-y),[1,2,3],[1,2,3])print map(None,[1,2,3],[1,2,3])print reduce(lambda x,y:x+y,[i for i in range(3)])from operator import  mul,addfrom functools import partialadd1 = partial(add,1)mul100 = partial(mul,100)basetwo = partial(int,base=2)basetwo.__doc__ = 'convert base 2 string to an int'print basetwo('10010')import Tkinterroot = Tkinter.Tk()mybutton = partial(Tkinter.Button,root,fg='white',bg='blue')b1 = mybutton(text='button1')b2 = mybutton(text='button2')qb = mybutton(text='quit',bg='red',command=root.quit)b1.pack()b2.pack()qb.pack(fill=Tkinter.X,expand=True)root.title('pfas!')root.mainloop()is_this_global = 'xyz'def foo():    global is_this_global    this_is_local = 'abc'    is_this_global = 'def'    print this_is_local + is_this_globaldef foor():    m = 3    def bar():        n = 4        print m + n    print m    bar()def counter(start=0):    count = [start]    def incr():        count[0] += 1        return count[0]    return incrcount = counter()output = '
 
  'w = x = y = z = 1def f1():    x = y = z = 2def f2():    y = z = 3    def f3():        z = 4        print output%('w',id(w),w)        print output%('x',id(x),x)        print output%('y',id(y),y)        print output%('z',id(z),z)    clo = f3.func_closure    if clo:        print 'f3 closure vars:',[str(c) for c in clo]    else:        print 'no f3 closure vars'    f3()    clo = f2.func_closure    if clo:        print 'f2 closure vars:',[str(c) for c in clo]    else:        print 'no f2 closure vars'    f2()    clo = f1.func_closure    if clo:        print 'f1 closure vars:',[str(c) for c in clo]    else:        print 'no f1 closure vars'from time import timedef logged(when):    def log(f,*args,**kargs):        print '''called:function:%sargs:%skargs:%s'''%(f,args,kargs)    def pre_logged(f):        def wrapper(*args,**kargs):            log(f,*args,**kargs)            return f(*args,**kargs)        return wrapper    def post_logged(f):        def wrapper(*args,**kargs):            now = time()            try:                return f(*args,**kargs)            finally:                log(f,*args,**kargs)                print 'time delta:%s' % (time()-now)        return wrapper    try:        return {'pre':pre_logged,'post':post_logged}[when]    except KeyError,e:        raise ValueError(e),"must be 'pre' or 'post'"@logged('post')def hello(name):    print 'hello,',namehello('world!')x = 10def ffoo():    y = 5    bar = lambda z:x+z    print bar(y)j,k = 1,2def proc1():    j,k = 3,4    print 'j==%d and k==%d'  % (j,k)def proc2():    j = 6    proc1()    print 'j==%d and k==%d' % (j,k)k = 7proc1()print 'j==%d and k==%d' % (j,k)j = 8proc2()print 'j==%d and k==%d' % (j,k)def max2(arg1,arg2):    if arg1 > arg2:        return arg1    elif arg1 == arg2:        return 'equal'    else:        return arg2max22 = lambda a,b:a if a > b else bmin22 = lambda a,b:a if a < b else bdef heji(a,b):    return a+b,a*bx,y = heji(3,4)def mymin(a,b,*num):    minnum = min22(a,b)    for each in num:        minnum = min22(minnum,each)    return minnumdef mymax(a,b,*num):    maxnum = max22(a,b)    for each in num:        maxnum = max22(maxnum,each)    return maxnumtrantime = lambda m:(unicode(m / 60),unicode(m % 60))print ':'.join(trantime(80))a = ['jia','wo','ma']b = ['get','hoa','?']print map(None,a,b)print zip(a,b)def oddyear(y):    if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:        return yprint filter(oddyear,range(1999,2030))print [y for y in range(1999,2030) if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0]print reduce(lambda x,y:x+y,range(6)) / float(6)cl = lambda x:x.strip()res = map(cl,open('e:\\thefile.txt'))import timedef timeit(arg):    starttime = time.clock()    result = arg    endtime = time.clock()    return (result,endtime-starttime)def arg(a,b):    return a * bprint timeit(arg(3,4))mult = lambda x,y:x * yprint reduce(mult,range(9)[1:])
 

The above is the function and function programming content of the Python basic learning code. For more information, see PHP Chinese network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.