为了账号安全,请及时绑定邮箱和手机立即绑定

python练习题

一、函数

1、用户传入修改的文件名,指定要修改的内容,执行函数,完成批量修改的操作

12345678910def modify_file(filename,old,new):    import os    with open(filename,'r',encoding='utf-8') as read_f,open('.bak.swap','w',encoding='utf-8') as write_f:        for line in read_f:            if old in line:                line=line.replace(old,new)            write_f.write(line)          #修改过的内容写到临时文件.bak.swap    os.remove(filename)                  #将源文件删除    os.rename('.bak.swap',filename)          #将临时文件.bak.swap重命名为之前的文件名filenamemodify_file('/Users/jieli/a.txt','some','same')    #用户传递参数,实现将a.txt中的some改为same

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

12345678910111213141516171819def check(msg):    res = {        'num'0,        'string'0,        'space'0,        'other'0,    }    for in msg:        if s.isdigit():             #判断属于数字            res['num'+= 1        elif s.isalpha():           #判断属于字符串            res['string'+= 1        elif s.isspace():           #判断属于空格            res['space'+= 1        else:            res['other'+= 1    return resres = check('hello name:jim passowrd:win2008')   #给函数传入参数‘hello name:jim passowrd:win2008’print(res)                           #结果是{'num': 4, 'string': 23, 'space': 2, 'other': 2}

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5

1234567891011121314151617def func1(str,list,tup):    zi = len(str)    li = len(list)    tup = len(tup)    if zi > 5:        print("字符串长度大于5")    else:        print("字符串长度小于或等于5")    if li > 5:        print("列表长度大于5")    else:        print("列表长度小于或等于5")    if tup > 5:        print("元组长度大于5")    else:        print("元组长度小于或等于5")func1("kwkwqehk",[11,22,33],(1,"215",5,6,59,6))

4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

12345def func1(seq):    if len(seq) > 2:        seq=seq[0:2]           #根据索引取元素,索引为0和1的    return seqprint(func1([1,2,3,4]))            #结果是[1, 2]

5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者

123def func2(seq):    return seq[::2]            #按照索引判断,指定步长为2print(func2((1,2,3,4,5,6,7)))       #结果是(1, 3, 5, 7)

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

1234567def func3(dic):    d={}    for key,value in dic.items():        if len(value) > 2:           #value长度大于2的            d[key]=value[0:2]       #新的value保留两个长度的内容,并和key组成新字典d    return dprint(func3({'k1':'abcdef','k2':[1,2,3,4],'k3':('a','b','c')}))    #结果是{'k1': 'ab', 'k2': [1, 2], 'k3': ('a', 'b')}

二、装饰器

1、写一个执行的时间是随机的函数

123456import randomimport timedef func1():    time.sleep(random.randrange(1,5))    #random的randrange生成随机的时间1到4秒    print('welecome to func1')func1()

2、编写装饰器,为函数加上统计时间的功能

12345678910111213141516import timeimport randomfrom functools import wrapsdef wrap(func):    def auth(*args,**kwargs):        start = time.time()        res=func(*args, **kwargs)        stop = time.time()        print('run time is %s' % (stop - start))        return res    return auth@wrap              #装饰器语法,相当于执行wrap(func)def func():    time.sleep(random.randrange(15))    print('welecome to func')func()

3、编写装饰器,为函数加上认证的功能

123456789101112131415161718import timedef wrap(func):    def auth(*args,**kwargs):        while True:            name=input('username: ').strip()            password=input('pwd: ').strip()            if name=='wang' and password=='123':                print('successful')                res=func(*args, **kwargs)                return res            else:                print('error')                continue    return auth@wrapdef index():    print('welecome to func1')index()

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

db文件内容:{'alex':'123','wang':'123'}


1234567891011121314151617181920212223242526272829303132login_status={'user':None,'status':False}           #用户输入一次,不管正确还是错误都结束程序def auth(auth_type='file'):    def auth2(func):        def wrapper(*args,**kwargs):            if login_status['user'and login_status['status']:                return func(*args,**kwargs)            if auth_type == 'file':                with open(r'C:\Users\db',encoding='utf-8') as f:                    dic=eval(f.read())                name=input('username: ').strip()                password=input('password: ').strip()                if name in dic and password == dic[name]:                    login_status['user']=name                    login_status['status']=True                    res=func(*args,**kwargs)                    return res                else:                    print('username or password error')            elif auth_type == 'sql':                print('from sql')            else:                print('error press')        return wrapper    return auth2@auth()def index():    print('index')@auth(auth_type='file')def home(name):    print('welcome %s to home' %name)index()home('wang')

5、编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录

12345678910111213141516171819202122232425262728293031323334import time,randomuser={'user':None,'login_time':None,'timeout':3.000003,}def timmer(func):    def wrapper(*args,**kwargs):        s1=time.time()        res=func(*args,**kwargs)        s2=time.time()        print('%s' %(s2-s1))        return res    return wrapperdef auth(func):    def wrapper(*args,**kwargs):        if user['user']:            timeout=time.time()-user['login_time']            if timeout < user['timeout']:                return func(*args,**kwargs)        name=input('name>>: ').strip()        password=input('password>>: ').strip()        if name == 'egon' and password == '123':            user['user']=name            user['login_time']=time.time()            res=func(*args,**kwargs)            return res    return wrapper@authdef index():    time.sleep(random.randrange(3))    print('welcome to index')@authdef home(name):    time.sleep(random.randrange(3))    print('welcome %s to home ' %name)index()home('wang')

6、编写日志装饰器,一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中

1234567891011121314151617import timeimport osdef logger(logfile):    def deco(func):        if not os.path.exists(logfile):                   #日志文件不存在pass            with open(logfile,'w'):pass        def wrapper(*args,**kwargs):            res=func(*args,**kwargs)            with open(logfile,'a',encoding='utf-8') as f:         #文件里面追加时间标记                f.write('%s %s run\n' %(time.strftime('%Y-%m-%d %X'),func.__name__))            return res        return wrapper    return deco@logger(logfile='aaa.log')def index():    print('index')index()

三、声明式编程练习

1、将names=['zhao','qian','sun','li']中的名字全部变大写

12names=[name.upper() for name in names]print(names)

2、将names=['zhao','qian','sun','li']中以i结尾的过滤掉,保存剩下的名字长度

12names=[name for name in names if not name.endswith('sb')]print(names)                             #结果['zhao', 'qian', 'sun']

3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)

123with open('aaa.log','r',encoding='utf-8') as f:    res=max(len(line) for line in f)    print(res)

4、文件shopping.txt内容如下

mac 20000 3

lenovo 3000 10

tesla 1000000 10

chicken 200 1

(1)开支是多少

12345with open('shopping.txt', encoding='utf-8') as f:    info = [line.split() for line in f]    #print(info)           #[['mac', '20000', '3'], ['lenovo', '3000', '10'], ['tesla', '1000000', '10'], ['chicken', '200', '1']]    cost = sum(float(unit_price) * int(count) for _, unit_price, count in info)        print(cost)           #结果是支出的金额

(2)打印信息,如格式为[{'name':'xxx','price':333,'count':3},...]

1234567with open('a.txt',encoding='utf-8') as f:    info=[{        'name': line.split()[0],        #取第一列的名字        'price'float(line.split()[1]),   #取第二列的价钱  转化为float类型        'count'int(line.split()[2]),    #取第三列的个数    int类型    for line in f]    print(info)

(3)单价大于10000的商品信息

1234567with open('a.txt',encoding='utf-8') as f:    info=[{        'name': line.split()[0],        'price'float(line.split()[1]),        'count'int(line.split()[2]),    for line in if float(line.split()[1])>10000]    print(info)





点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消