python练习题,,一、函数1、用户传入


一、函数

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

defmodify_file(filename,old,new):importoswithopen(filename,'r',encoding='utf-8')asread_f,open('.bak.swap','w',encoding='utf-8')aswrite_f:forlineinread_f:ifoldinline:line=line.replace(old,new)write_f.write(line)#修改过的内容写到临时文件.bak.swapos.remove(filename)#将源文件删除os.rename('.bak.swap',filename)#将临时文件.bak.swap重命名为之前的文件名filenamemodify_file('/Users/jieli/a.txt','some','same')#用户传递参数,实现将a.txt中的some改为same

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

defcheck(msg):res={'num':0,'string':0,'space':0,'other':0,}forsinmsg:ifs.isdigit():#判断属于数字res['num']+=1elifs.isalpha():#判断属于字符串res['string']+=1elifs.isspace():#判断属于空格res['space']+=1else:res['other']+=1returnresres=check('helloname:jimpassowrd:win2008')#给函数传入参数‘helloname:jimpassowrd:win2008’print(res)#结果是{'num':4,'string':23,'space':2,'other':2}

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

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

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

deffunc1(seq):iflen(seq)>2:seq=seq[0:2]#根据索引取元素,索引为0和1的returnseqprint(func1([1,2,3,4]))#结果是[1,2]

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

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

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

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

二、装饰器

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

importrandomimporttimedeffunc1():time.sleep(random.randrange(1,5))#random的randrange生成随机的时间1到4秒print('welecometofunc1')func1()

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

importtimeimportrandomfromfunctoolsimportwrapsdefwrap(func):defauth(*args,**kwargs):start=time.time()res=func(*args,**kwargs)stop=time.time()print('runtimeis%s'%(stop-start))returnresreturnauth@wrap#装饰器语法,相当于执行wrap(func)deffunc():time.sleep(random.randrange(1,5))print('welecometofunc')func()

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

importtimedefwrap(func):defauth(*args,**kwargs):whileTrue:name=input('username:').strip()password=input('pwd:').strip()ifname=='wang'andpassword=='123':print('successful')res=func(*args,**kwargs)returnreselse:print('error')continuereturnauth@wrapdefindex():print('welecometofunc1')index()

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

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


login_status={'user':None,'status':False}#用户输入一次,不管正确还是错误都结束程序defauth(auth_type='file'):defauth2(func):defwrapper(*args,**kwargs):iflogin_status['user']andlogin_status['status']:returnfunc(*args,**kwargs)ifauth_type=='file':withopen(r'C:\Users\db',encoding='utf-8')asf:dic=eval(f.read())name=input('username:').strip()password=input('password:').strip()ifnameindicandpassword==dic[name]:login_status['user']=namelogin_status['status']=Trueres=func(*args,**kwargs)returnreselse:print('usernameorpassworderror')elifauth_type=='sql':print('fromsql')else:print('errorpress')returnwrapperreturnauth2@auth()defindex():print('index')@auth(auth_type='file')defhome(name):print('welcome%stohome'%name)index()home('wang')

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

importtime,randomuser={'user':None,'login_time':None,'timeout':3.000003,}deftimmer(func):defwrapper(*args,**kwargs):s1=time.time()res=func(*args,**kwargs)s2=time.time()print('%s'%(s2-s1))returnresreturnwrapperdefauth(func):defwrapper(*args,**kwargs):ifuser['user']:timeout=time.time()-user['login_time']iftimeout<user['timeout']:returnfunc(*args,**kwargs)name=input('name>>:').strip()password=input('password>>:').strip()ifname=='egon'andpassword=='123':user['user']=nameuser['login_time']=time.time()res=func(*args,**kwargs)returnresreturnwrapper@authdefindex():time.sleep(random.randrange(3))print('welcometoindex')@authdefhome(name):time.sleep(random.randrange(3))print('welcome%stohome'%name)index()home('wang')

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

importtimeimportosdeflogger(logfile):defdeco(func):ifnotos.path.exists(logfile):#日志文件不存在passwithopen(logfile,'w'):passdefwrapper(*args,**kwargs):res=func(*args,**kwargs)withopen(logfile,'a',encoding='utf-8')asf:#文件里面追加时间标记f.write('%s%srun\n'%(time.strftime('%Y-%m-%d%X'),func.__name__))returnresreturnwrapperreturndeco@logger(logfile='aaa.log')defindex():print('index')index()

三、声明式编程练习

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

names=[name.upper()fornameinnames]print(names)

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

names=[namefornameinnamesifnotname.endswith('sb')]print(names)#结果['zhao','qian','sun']

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

withopen('aaa.log','r',encoding='utf-8')asf:res=max(len(line)forlineinf)print(res)

4、文件shopping.txt内容如下

mac 20000 3

lenovo 3000 10

tesla 1000000 10

chicken 200 1

(1)开支是多少

withopen('shopping.txt',encoding='utf-8')asf:info=[line.split()forlineinf]#print(info)#[['mac','20000','3'],['lenovo','3000','10'],['tesla','1000000','10'],['chicken','200','1']]cost=sum(float(unit_price)*int(count)for_,unit_price,countininfo)print(cost)#结果是支出的金额

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

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

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

withopen('a.txt',encoding='utf-8')asf:info=[{'name':line.split()[0],'price':float(line.split()[1]),'count':int(line.split()[2]),}forlineinfiffloat(line.split()[1])>10000]print(info)





python练习题

评论关闭