美文网首页
python视频笔记之三(循环和函数)

python视频笔记之三(循环和函数)

作者: 缺月挂梧桐 | 来源:发表于2016-05-31 20:38 被阅读0次

    while循环

    while expression: 

        statement(s)

    x=""
    while x!="q":
       print "hello"
       x=raw_input("please input somethin. q for quit:")
       if not x:                          如果输入的x为空时,退出
           break 
     else:
        print "ending..."

    函数

     def 函数名(参数列表): #可以没有参数
           函数体

     def add():
        c=a+b
        print c

    t=('name','milo') 作为一个元组
    def f(x,y):
        print "%s:%s"%(x,y)

    调用 f(*t)得到结果 name:milo

    匿名函数 

      lambda表达式
         g= lambda x,y:x*y
         g(2,3)

    阶乘 5!=5*4*3*2*1  函数的递归调用
    l=range(1,6)       l的值是[1,2,3,4,5]
    def f(x,y):
        return x*y
    reduce(f,l)   reduce得到5的阶乘,值是120

    f=lambda x,y:x*y
    reduce(f,l)   得到值120


    python通过字典实现switch语句的功能

    首先定义一个字典,其它调用字典的get()获取相应的表达式。

    from __future__ import division      块

    print 3.00/2

    print 4/3

    from __future__ import division

    def jia(x,y):return x+y

    def jian(x,y):return x-y

    def cheng(x,y):return x*y

    def chu(x,y):return x/y

    operator={"+":jia,"-":jian,"*":cheng,"/":chu}

    def f(x,o,y):print operator.get(o)(x,y)

    f(3,"+",2)

    f(3,"/",2)

    from __future__ import division 

    x=1

    y=2

    operator="/"

    result={"+":x+y,"-":x-y,"*":x*y,"/":x/y}

    print result.get(operator)


    常用函数

    abs(-10)    max(10,2,9)    min(2,3,5)



    l=[2,34,4]

    print max(l)    取最大值

    print len(l)      统计元素个数

    print divmod(9,2)   得出除数的结果和余数

    print pow(4,3)     等于 4*4*4

    print round(7.6)    四舍五入

    help(divmod)   获取函数的帮助

    callable()    测试某个函数是否被调用   callable(min) 返回true
    isinstance() 判断某个对象返回类型  isinstance(l,int)判断l是否是个int型
    cmp()
    range(10) 快速生成一个序列
    xrange(10)生成一个序列

    type()
    int()
    float()等类型转换函数


    l=[2,34,4]

    s="hello word"

    print s.capitalize()

    print s.replace(s, "world")

    def f(x):

    if x>5:

    return True

    print filter(f,l)       

    #coding=utf-8

    l=[2,34,4]

    s="hello word"

    print s.capitalize()

    print s.replace(s, "world")

    def f(x):

    if x>5:

    return True

    print filter(f,l)    #从l中找出大于于5的数

    name=['milo','zou']

    age=[20,30]

    print zip(name,age)    #得到结果[('milo', 20), ('zou', 30)]

    a=[1,3,5]

    b=[2,4,6]

    print map(None,a,b)  #得到结果[(1, 2), (3, 4), (5, 6)]

    l=range(1,101)    #得到1到100的数

    def rf(x,y):

    return x+y

    print reduce(rf,l)  #从1累加到100的值,得到结果5050

    print reduce(lambda x,y:x+y,l)  #用内建函数得到结果5050

    print filter(lambda x:x%2==0,l) #得到偶数 值

    相关文章

      网友评论

          本文标题:python视频笔记之三(循环和函数)

          本文链接:https://www.haomeiwen.com/subject/qimsrttx.html