zoukankan      html  css  js  c++  java
  • Python练习七

    1.写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

    def func(dic):
        for k in dic:
            if len(dic[k]) > 2:
                dic[k] = dic[k][:2]
        return dic
    
    
    dic = {"name": "风光无极", "adress": "3435", "s": "erre34", "s": [2, 3, 4, 5], "s": "3"}
    
    print(func(dic))

    2.写函数,接收两个数字参数,并返回比较大的那个数字。

    def func(x, y):
        return x if x > y else y
    
    
    print(func(5, 8))

    3.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码。

    FLAG = False
    
    
    def login(func):
        def inner(*args, **kwargs):
            global FLAG
            if FLAG:
                ret = func(*args, **kwargs)
                return ret
            else:
                username = input('请输入用户名:')
                password = input('请输入密码:')
                if username == '林彬' and password == '123':
                    FLAG = True
                    ret = func(*args, **kwargs)
                    return ret
                else:
                    print("用户名或密码错误")
    
        return inner
    
    
    @login
    def name():
        print("赖玉英")
    
    
    @login
    def love():
        print('大狗屎')
    
    
    name()
    love()

    4.编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名写入文件。

    def log(func):
        def inner(*args, **kwargs):
            ret = func(*args, **kwargs)
            with open('log', 'a', encoding='utf-8') as f:
                f.write(func.__name__ + '
    ')
            return ret
    
        return inner
    
    
    @log
    def love():
        print('赖狗屎我爱你')
    
    
    @log
    def love2():
        print('赖狗屎吃狗屎')
    
    
    @log
    def love3():
        print('赖美女我爱你')
    
    
    love3()
    love2()
    love()
    love3()

    5.监听文件输入的列子。

    def func(filename):
        with open(filename, encoding='utf-8') as f:
            while 1:
                line = f.readline()
                if line.strip():
                    yield line.strip()
    
    
    g = func('file')
    for i in g:
        print(i)
  • 相关阅读:
    [BZOJ3195][Jxoi2012]奇怪的道路
    [codeforces696B]Puzzles
    [codeforces464D]World of Darkraft
    [COGS1000]伊吹萃香 最短路
    [BZOJ4653][NOI2016]区间 贪心+线段树
    [BZOJ4540][HNOI2016]序列 莫队
    [BZOJ4870][Shoi2017]组合数问题 dp+矩阵乘
    Loj 2005 相关分析
    Loj 114 k大异或和
    bzoj 2212 Tree Rotations
  • 原文地址:https://www.cnblogs.com/lin961234478/p/10598673.html
Copyright © 2011-2022 走看看