1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 __author__ = 'Howie' 4 ''' 5 作业要求: 6 1.输入用户密码 7 2.认证后显示欢迎信息 8 3.输错三次后锁定 9 ''' 10 ############################## 11 ''' 12 readme: 13 这是一个登陆接口脚本,要求输入正确的用户名和密码,如果输入三次失败后将被锁定。 14 现在还有一个BUG就是三次输入错误的时候只会调取最一次的用户名来锁定。 15 ''' 16 account_file = 'user.txt' 17 lock_file = 'account_lock.txt' 18 userpass = 'F' 19 count = 0 20 while userpass == 'F' and count <3: 21 Username = input('输入用户名:') 22 Password = input('输入密码:') 23 count +=1 24 with open(lock_file,'r') as f: #打开锁定用户列表 25 for line in f.readlines(): #遍历文档每一行 26 username = line.strip() #把每一行的字符串以空格分拆,并且赋值 27 if Username == username: #判断用户是否在锁表中 28 print('您的账户被锁定') 29 userpass = 'L' 30 break 31 if userpass == 'L':#当被标记为L时跳出white循环 32 break 33 with open(account_file,'r') as f: #打开用户列表 34 for line in f.readlines(): #遍历文档每一行 35 username,password = line.strip().split() #把每一行的字符串以空格分拆,并且赋值 36 if Username == username and Password == password:#判断用户名和密码都正确 37 print('成功登陆') 38 userpass = 'T' 39 break #成功校验后标记为T并且跳出当前循环到while判断标记为T然后跳出所有循环 40 if count >=3 and userpass == 'F':#精确判断次数和标记 41 print("错误次数过多,账号被锁") 42 with open(lock_file,'a+') as L: 43 L.write(' ') 44 L.write(Username)
这个是我第一次用python写那么多的代码
写得很差
我觉得最重要的就是要分清楚循环的等级关系就可以了
OK 复习的时候重新再写过的
1 import json, os 2 coun = 0 3 while True: 4 in_username = input('username:') 5 in_pwd = input('pwd:') 6 USER_PATH = in_username + '.json' #这里是用字符拼接把输入的用户名和后缀名连上 7 8 BASEDIR = os.path.join(os.path.abspath('user'), USER_PATH) #找到数据文件的路径 9 try:#这里是try来抛异常为了如果找不到文件的时候不要报错 10 datadict = json.load(open(BASEDIR)) #JSON的读取格式化就是把json序列化成字典 11 username = datadict['username'] 12 pwd = datadict['pwd'] 13 status = datadict['status'] 14 if status == 0: 15 if in_username == username and in_pwd == pwd: #这里就验证登录 16 print('欢迎') 17 break 18 else: 19 coun += 1 20 if coun >= 3: 21 print('被锁定') 22 datadict['status'] = 1 23 print(datadict) 24 with open(BASEDIR, 'w') as f: #这里就是要打一个文件并且可以写入的 25 json.dump(datadict, f) #json的反序列化还有写回到文件 26 break 27 print('用户密码错误再试试,您的次数还有', 3 - coun, '次') 28 else: 29 print('用户被锁定') 30 break 31 except: 32 print('没有这个用户')