python基础题目计算_PYTHON基础练习题

1、持续输入数据、输完之后退出

ContractedBlock.gif

ExpandedBlockStart.gif

with open('test4.txt','w',encoding='utf-8') as f:whileTrue:

inp= input("请输入内容:")if inp == 'q':breakf.write(inp+ '\n')

with open('test4.txt','r',encoding='utf-8') as f:print(f.read())

View Code

2、验证用户名和密码,用户名和密码存在文件中

ContractedBlock.gif

ExpandedBlockStart.gif

with open('test3.py',encoding='utf8') as f:

d=dict()for line inf:

vvv=line.strip('\n').split(":")[0]

kkk=line.strip('\n').split(":")[1]if notlen(line):continued[vvv]=kkkwhileTrue:

a= input("用户名:").strip()

b= input("密码:").strip()if a in d.keys() and b ==d[a]:print("登陆成功")else:print("用户名或密码错误")

View Code

3、生成5位的随机验证码

ContractedBlock.gif

ExpandedBlockStart.gif

importrandom

sts= ''

for i in range(5):

sts+= random.choice([str(random.randint(0,9)),chr(random.choice([random.randint(65,90),random.randint(97,122)]))])print(sts)#65-90对应小写字母、97-122对应大写字母

View Code

4、题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

ContractedBlock.gif

ExpandedBlockStart.gif

lis = [1,2,3,4]

k=[]for a inlis:for b inlis:for c inlis:

d=str(a)+str(b)+str(c)if d[0] != d[1] and d[1] != d[2] and d[0] !=d[2]:

k.append(int(d))print(len(k))print(k)24[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]

View Code

5、使用循环实现修改文件内容

ContractedBlock.gif

ExpandedBlockStart.gif

importosdefmodify(filename,old,new):

with open('test.log','r',encoding='utf8') as read_f,\#换行书写

open('bak.swap','w',encoding='utf8') as write_f:for line inread_f:if old inline:

line=line.replace(old,new)

write_f.write(line)

os.remove(filename)

os.rename('bak.swap',filename)

modify('test.log','test','TEST')

View Code

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

ContractedBlock.gif

ExpandedBlockStart.gif

defdecide(st):

dig=0      #此处也可以将类型和数量放到字典中,函数最后返回字典

alp=0

spa=0

oth=0for i inst:ifi.isdecimal():

dig=dig+1        #等于dig+=1,要注意和dig=+1的区别(=+并不是简写,a =+ a直接对a的赋值,±符号代表的是正负,即a =+ b其实就是a = b)

elifi.isalpha():

alp=alp+1

elifi.isspace():

spa=spa+1

else:

oth=oth+1

print("数字个数:%s 字母个数:%s 空格个数:%s 其他个数:%s"%(dig,alp,spa,oth))

decide('asdaadsdasd123123123 !@#$%^&')

View Code

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

ContractedBlock.gif

ExpandedBlockStart.gif

defdecide(st):if len(st) > 5:print("大于5")else:print("长度小于等于5")

decide('asdad')

View Code

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

ContractedBlock.gif

ExpandedBlockStart.gif

defdecide(lis):if len(lis) > 2:

lis=lis[0:2]returnlisprint(decide([1,2,3,4,4]))

View Code

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

ContractedBlock.gif

ExpandedBlockStart.gif

defchoice(seq):

lis=[]for i inseq:if seq.index(i)%2 !=0:

lis.append(i)returnlis

a=['a','b','c','d','e','f','g','h']print(choice(a))

或者采用切片的方式:deffunc2(seq):return seq[::2]print(func2([1,2,3,4,5,6,7]))

View Code

10、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。字典中的value只能是字符串或列表

ContractedBlock.gif

ExpandedBlockStart.gif

di = {"k1": "v1v1", "k2": [11,22,33,44]}deftake(dic):for value,key indic.items():if len(key) >2:print(key)

dic[value]=key[:2]returndicprint(take(di))

View Code

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

ContractedBlock.gif

ExpandedBlockStart.gif

importtime,randomdefcal():

st_t=time.time()

time.sleep(random.randint(0,9))

ed_t=time.time()

all= ed_t-st_tprint("函数执行时间是:%s秒"%all)

cal()

View Code

12、利用装饰器计算函数运行时间

ContractedBlock.gif

ExpandedBlockStart.gif

importtime,randomdeftimer(fun):defwrapper():

st_t=time.time()

fun()

ed_t=time.time()

all= ed_t -st_tprint("函数执行时间是:%s秒" %all)returnwrapper

@timer#test=tiemr(test)

defcal():

time.sleep(random.randint(0,9))

cal()

View Code

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

ContractedBlock.gif

ExpandedBlockStart.gif

importtime,randomdeftimer(fun):defwrapper():

with open('test3.py', encoding='utf8') as f:

d=dict()for line inf:

vvv= line.strip('\n').split(":")[0]

kkk= line.strip('\n').split(":")[1]if notlen(line):continued[vvv]=kkkwhileTrue:

a= input("用户名:").strip()

b= input("密码:").strip()if a in d.keys() and b ==d[a]:print("登陆成功")break

else:print("用户名或密码错误")

fun()returnwrapper

@timerdefcal():

time.sleep(random.randint(0,9))print("函数执行成功!")

cal()

View Code

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

注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式

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(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':

pass

else:

pass

return wrapper  #返回给auth2

return auth2  #返回给@auth

@auth()注意这里是带()的,代表运行

def index():

print('index')

index()

@auth(auth_type='file')

def home(name):

print('welcome %s to home' %name)

#找时间再练一下

15、利用迭代器原理读取文件内容

ContractedBlock.gif

ExpandedBlockStart.gif

t=open('haproxy.conf').__iter__()while 1:try:print(t.__next__(), end='')exceptStopIteration:break

View Code

16、

# 1、文件内容如下,标题为:姓名,性别,年纪,薪资

# egon male 18 3000

# alex male 38 30000

# wupeiqi female 28 20000

# yuanhao female 28 10000

#

# 要求:

# 从文件中取出每一条记录放入列表中,

# 列表的每个元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式

with open('test3.py') as f:

lis=( line.split() for line inf )

info=[{'name':name,'sex':sex,'age':age,'salary':salary} for name,sex,age,salary inlis]print(info)#根据1得到的列表,取出薪资最高的人的信息

print(max(info,key=lambda dic:dic['salary']))#根据1得到的列表,取出最年轻的人的信息

print(max(info,key=lambda dic:dic['age']))#根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式

for dic ininfo:

dic['name']=dic['name'].title()print(info)

17、九九乘法表

for i in range(1,10):

for j in range(1,i+1):

print("%d * %d = %d\t"%(i,j,i*j),end='')

print()

18、电子书自动翻页,可以选择手动翻页

ContractedBlock.gif

ExpandedBlockStart.gif

importtimedef read(file,line=1):

with open(file,'r',encoding='utf8') as f:

f.seek(0,2)

end=f.tell()

f.seek(0,0)

inp=input("是否开启自动模式(y/n)")if inp == 'y':whileTrue:for i inrange(line):print(f.readline(),end='')

time.sleep(1)

cur=f.tell()if cur ==end:print("牛逼啊看完了")break

else:

choice='n'f.seek(0,2)

end=f.tell()

f.seek(0, 0)whileTrue:for i inrange(line):print(f.readline(),end='')#else:

#print("输入n翻页")

if f.tell() ==end:print("牛逼啊看完了")breakchoice=input(">>>")

read('1.txt')

View Code

19、用户登录验证简单版:

ContractedBlock.gif

ExpandedBlockStart.gif

dic = {'aaa':123,'sss':123,'bbb':123}

count=0whileTrue:

name=input('请输入用户名:')

mima=input('请输入密码:')try:

mima=int(mima)except:print("请输入数字密码")

exit(1)if name in dic.keys() and mima ==dic[name]:print('恭喜%s登陆成功!'%name)else:print('用户名或密码错误')

count+= 1

if count == 3:print('验证错误超过3次,程序退出')break

View Code

20、斐波那契数列

a=1

b=1

for fn in range(2,100):

if fn == b + a:

print(fn)

a,b=b,fn

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值