一、函数
1、用户传入修改的文件名,指定要修改的内容,执行函数,完成批量修改的操作
| 12345678910 | def 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) |
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
| 12345678910111213141516171819 | def check(msg): res = { 'num': 0, 'string': 0, 'space': 0, 'other': 0, } for s in msg: if s.isdigit(): |
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5
| 1234567891011121314151617 | def 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,那么仅保留前两个长度的内容,并将新内容返回给调用者。
| 12345 | def func1(seq): if len(seq) > 2: seq=seq[0:2] |
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者
| 123 | def func2(seq): return seq[::2] |
6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者
| 1234567 | def func3(dic): d={} for key,value in dic.items(): if len(value) > 2: |
二、装饰器
1、写一个执行的时间是随机的函数
| 123456 | import randomimport timedef func1(): time.sleep(random.randrange(1,5)) |
2、编写装饰器,为函数加上统计时间的功能
| 12345678910111213141516 | import 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 |
3、编写装饰器,为函数加上认证的功能
| 123456789101112131415161718 | import 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'}
| 1234567891011121314151617181920212223242526272829303132 | login_status={'user':None,'status':False} |
5、编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
| 12345678910111213141516171819202122232425262728293031323334 | import 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写入到日志文件中
| 1234567891011121314151617 | import timeimport osdef logger(logfile): def deco(func): if not os.path.exists(logfile): |
三、声明式编程练习
1、将names=['zhao','qian','sun','li']中的名字全部变大写
| 12 | names=[name.upper() for name in names]print(names) |
2、将names=['zhao','qian','sun','li']中以i结尾的过滤掉,保存剩下的名字长度
| 12 | names=[name for name in names if not name.endswith('sb')]print(names) |
3、求文件a.txt中最长的行的长度(长度按字符个数算,需要使用max函数)
| 123 | with 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)开支是多少
| 12345 | with open('shopping.txt', encoding='utf-8') as f: info = [line.split() for line in f] |
(2)打印信息,如格式为[{'name':'xxx','price':333,'count':3},...]
| 1234567 | with open('a.txt',encoding='utf-8') as f: info=[{ 'name': line.split()[0], |
(3)单价大于10000的商品信息
| 1234567 | with 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 f if float(line.split()[1])>10000] print(info) |