• 小练习函数


    #2、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
    # def func(l):
    #     return l[1::2]  #切片
    # print(func([1,2,3,4,5]))
    
    # 3、写函数,判断用户传入的值(字符串、列表、元组)长度是否大于5。
    # def func(x):
    #     return len(x)>5
    # if func('abcd'):
    #     print('长度确实大于5')
    
    # 4、写函数,检查传入列表的长度,如果大于2,
    # 那么仅保留前两个长度的内容,并将新内容返回给调用者。
    # def func(l):
    #     return l[:2]
    #
    # print(func([1,2,3,4]))
    
    # 5、写函数,计算传入字符串中【数字】、【字母】、【空格】 以及 【其他】的个数,并返回结果。
    # def func(s):   #'skghfoiw8qpeuqkd'
    #     dic = {'num':0,'alpha':0,'space':0,'other':0}
    #     for i in s:
    #         if i.isdigit():
    #             dic['num']+=1
    #         elif i.isalpha():
    #             dic['alpha'] += 1
    #         elif i.isspace():
    #             dic['space'] += 1
    #         else:
    #             dic['other'] += 1
    #     return dic
    # print(func('+0-0skahe817jashf wet1'))
    
    # 6、写函数,检查用户传入的对象(字符串、列表、元组)
    # 的每一个元素是否含有空内容,并返回结果。
    # def func(x):
    #     if type(x) is str and x:  #参数是字符串
    #         for i in x:
    #             if i == ' ':
    #                 return True
    #     elif x and type(x) is list or type(x) is tuple: #参数是列表或者元组
    #         for i in x:
    #             if not i:
    #                 return True
    #     elif not x:
    #         return True
    #
    # print(func([]))
    
    #7、写函数,检查传入字典的每一个value的长度,如果大于2,
    # 那么仅保留前两个长度的内容,并将新内容返回给调用者。
    #    dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    #    PS:字典中的value只能是字符串或列表
    # def func(dic):
    #     for k in dic:
    #         if len(dic[k]) > 2:
    #             dic[k] = dic[k][:2]
    #     return dic
    # dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    # print(func(dic))
    
    # 8、写函数,接收两个数字参数,返回比较大的那个数字。
    # def func(a,b):
    #     if a>b:
    #         return a
    #     else:
    #         return b
    # print(func(1,5))
    
    # def func(a,b):
    #     return a if a > b else b
    # print(func(5,1))
    
    # 三元运算
    # a = 1
    # b = 5
    # c = a if a>b else b   #三元运算
    # print(c)
    
    # 变量 = 条件返回True的结果 if 条件 else 条件返回False的结果
    #必须要有结果
    #必须要有if和else
    #只能是简单的情况
    
    # 9、写函数,用户传入修改的文件名,与要修改的内容,
    # 执行函数,完成整个文件的批量修改操作(进阶)。
    # def func(filename,old,new):
    #     with open(filename, encoding='utf-8') as f, open('%s.bak'%filename, 'w', encoding='utf-8') as f2:
    #         for line in f:
    #             if old in line:  # 班主任:星儿
    #                 line = line.replace(old,new)
    #             # 写文件
    #             f2.write(line)  # 小护士:金老板
    #
    #     import os
    #     os.remove(filename)  # 删除文件
    #     os.rename('%s.bak'%filename, filename)  # 重命名文件
    
    
    
    
    # 2、写函数,接收n个数字,求这些参数数字的和。
    def sum_func(*args):
        total = 0
        for i in args:
            total += i
        return total
    print(sum_func(1,2,3,8,23,6))
    
    # 3、读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么?
    #     a=10
    #     b=20
    #     def test5(a,b):
    #          print(a,b)
    #     c = test5(b,a)
    #     print(c)
    
    
    
    # 4、读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么?
    #     a=10
    #     b=20
    #     def test5(a,b):
    #         a=3
    #         b=5
    #          print(a,b)
    #     c = test5(b,a)
    #     print(c)
    
    
    # 1.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),
    # 要求登录成功一次,后续的函数都无需再输入用户名和密码
    # FLAG = False
    # def login(func):
    #     def inner(*args,**kwargs):
    #         global FLAG
    #         '''登录程序'''
    #         if FLAG:
    #             ret = func(*args, **kwargs)  # func是被装饰的函数
    #             return ret
    #         else:
    #             username = input('username : ')
    #             password = input('password : ')
    #             if username == 'boss_gold' and password == '22222':
    #                 FLAG = True
    #                 ret = func(*args,**kwargs)      #func是被装饰的函数
    #                 return ret
    #             else:
    #                 print('登录失败')
    #     return inner
    #
    # @login
    # def shoplist_add():
    #     print('增加一件物品')
    #
    # @login
    # def shoplist_del():
    #     print('删除一件物品')
    #
    # shoplist_add()
    # shoplist_del()
    
    # 2.编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名称写入文件
    # def log(func):
    #     def inner(*args,**kwargs):
    #         with open('log','a',encoding='utf-8') as f:
    #             f.write(func.__name__+'
    ')
    #         ret = func(*args,**kwargs)
    #         return ret
    #     return inner
    #
    # @log
    # def shoplist_add():
    #     print('增加一件物品')
    #
    # @log
    # def shoplist_del():
    #     print('删除一件物品')
    
    # shoplist_add()
    # shoplist_del()
    # shoplist_del()
    # shoplist_del()
    # shoplist_del()
    # shoplist_del()
    
    # 进阶作业(选做):
    # 1.编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
    # 2.为题目1编写装饰器,实现缓存网页内容的功能:
    # 具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
    import os
    from urllib.request import urlopen
    def cache(func):
        def inner(*args,**kwargs):
            if os.path.getsize('web_cache'):
                with open('web_cache','rb') as f:
                    return f.read()
            ret = func(*args,**kwargs)  #get()
            with open('web_cache','wb') as f:
                f.write(b'*********'+ret)
            return ret
        return inner
    
    @cache
    def get(url):
        code = urlopen(url).read()
        return code
    
    
    # {'网址':"文件名"}
    ret = get('http://www.baidu.com')
    print(ret)
    ret = get('http://www.baidu.com')
    print(ret)
    ret = get('http://www.baidu.com')
    print(ret)
    View Code

  • 相关阅读:
    HTTP基础及telnet简单命令
    【详解】并查集高级技巧:加权并查集、扩展域并查集
    二叉树中两节点的最近公共父节点(360的c++一面问题)
    (用POJ 1160puls来讲解)四边形不等式——区间dp的常见优化方法
    详细讲解Codeforces Round #625 (Div. 2)E
    详细讲解Codeforces Round #625 (Div. 2) D. Navigation System
    详细讲解Codeforces Round #624 (Div. 3) F. Moving Points
    详细讲解Codeforces Round #624 (Div. 3) E. Construct the Binary Tree(构造二叉树)
    POJ
    新手建站前需要做哪些准备?
  • 原文地址:https://www.cnblogs.com/bzluren/p/10624159.html
Copyright © 2020-2023  润新知