zoukankan      html  css  js  c++  java
  • 老王Python-进阶篇4-函数第五节

    '''
    1.定义一个func(name),该函数效果如下。
    assert func("lilei") = "Lilei"
    assert func("hanmeimei") = "Hanmeimei"
    assert func("Hanmeimei") = "Hanmeimei"
    '''

     1 def func(name):
     2     a=name.lower()
     3     return a.capitalize()
     4 
     5 
     6 print func("lilei")
     7 print func("hanmeimei")
     8 print func("Hanmeimei")
     9 
    10 
    11 assert func("lilei")=="Lilei"
    12 assert func("hanmeimei") =="Hanmeimei"
    13 assert func("Hanmeimei") == "Hanmeimei"

    """
    2.定义一个func(name,callback=None),效果如下。
    assert func("lilei") == "Lilei"
    assert func("LILEI",callback=string.lower) == "lilei"
    assert func("lilei",callback=string.upper) == "LILEI"

    """

     2 def func(name,callback=None):
     3      if callback==None:
     4           return name.capitalize()
     5      else:
     6         return callback(name)
     7 
     8  print func("lilei")
     9  print func("LILEI",callback=string.lower)
    10  print func("lilei",callback=string.upper)
    11 
    12  
    13  assert func("lilei") == "Lilei"
    14  assert func("LILEI",callback=string.lower) == "lilei"
    15  assert func("lilei",callback=string.upper) == "LILEI"

    """
    3.定义一个func(*kargs),效果如下。

    l = func(1,2,3,4,5)
    for i in l:
    print i,
    #输出 1 2 3 4 5

    l = func(5,3,4,5,6)
    for i in l:
    print i
    #输出 5 3 4 5 6

    """

    1 def getitem(*kargs):
    2     return kargs

    4.定义一个func(*kargs),该函数效果如下。

    assert func(222,1111,'xixi','hahahah') == "xixi"
    assert func(7,'name','dasere') == 'name'
    assert func(1,2,3,4) == None


    """

     1 def shortstr(*kargs):
     2    
     3     lis = filter(lambda x:isinstance(x,str),kargs)
     4  
     5     len_lis = [len(x) for x in lis]
     6 
     7     if len_lis:
     8             min_index = min(len_lis)
     9             return lis[len_lis.index(min_index)]
    10     return None

    """
    5.定义一个func(name=None,**kargs),该函数效果如下。

    assert func(“lilei”) == "lilei"
    assert func("lilei",years=4) == "lilei,years:4"
    assert func("lilei",years=10,body_weight=20) == "lilei,years:4,body_weight:20"

    """

    1 def func(name=None,**kargs):
    2     lis = ["%s:%s"%(k,v) for k,v in kargs.items()]
    3     lis.insert(0,name)
    4     return ','.join(lis)

    注:部分习题答案转载自“老王Python”

  • 相关阅读:
    python爬虫,scrapy,获取响应的cookie,获取返回的cookie
    this指向
    闭包的10种形式
    nodejs 公私钥文件加密解密
    mysql基础知识
    nodejs 连接mysql 集群,开启事务,事务回滚封装
    pm2 启动eggjs,
    js身份证验证,二代身份证,大陆,权重验证,正规
    nodejs限制IP一段时间内的访问次数
    nodejs链接mysql集群,nodejs PoolCluster : Error: Too many connections
  • 原文地址:https://www.cnblogs.com/duyaya/p/8120426.html
Copyright © 2011-2022 走看看