Python基础-用户验证
一、项目需求
1、根据用户名和密码,验证用户是否可登陆
2、允许一次执行可验证三次
3、当用户名输错三次后,该用户名锁定,永久不可登陆
二、代码如下
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 #import operator 4 n = 0 5 username="user123" 6 password="123.abc" 7 count_dict={} 8 tmp_dict={} 9 with open("lock",mode="r+",encoding="utf8") as f_read,open("lock_tmp",mode="a+",encoding="utf8") as f_write: 10 #lock文件和lock_tmp要先创建 11 while n<3: 12 name=input("please input username:").strip() 13 pwd=input("please input passwd:").strip() 14 for line in f_read: 15 if name in line: 16 print("当前用户已经被锁定,请联系管理员!!") 17 exit() 18 if name == username and pwd == password: 19 print("欢迎%s登录"%username) 20 exit() 21 else: 22 print("用户名或密码错误,请重新输入!") 23 f_write.write(name+"\n") 24 if name not in tmp_dict: 25 tmp_dict[name]=1 26 else: 27 tmp_dict[name]+=1 28 n+=1 29 # print(tmp_dict) 30 for line in f_write.readline(): 31 line = line.strip() 32 count = count_dict.setdefault(line,0) 33 count+=1 34 count_dict[line]=count 35 print(count_dict) 36 f_write.seek(0) 37 for k in count_dict.keys(): 38 print(k,count_dict[k]) 39 # print(count_dict[k]) 40 if count_dict[k] >= 3: 41 f_read.write(k+"\n") 42 for k1 in tmp_dict.keys(): 43 if tmp_dict[k1]>=3: 44 f_read.write(k1+"\n")