用户登录
#!/usr/bin/env python # -*- coding:utf-8 -*- # by wk ''' 说明: 如果登录用户在用户列表里,每个用户只有3次登录机会,失败后锁定账户,下次启动账户提示账户被锁定 如果登录用户不在用户列表里,提示用户不存在,并且尝试3次登录,如果失败退出程序 ''' import sys def checklock(username): with open("loginlock.txt", 'r') as lock_t: for line in lock_t.readlines(): if len(line) == 0: continue if username == line.strip(): print("login fail too much! User locked") # sys.exit() return 'lock' def userlock(username): f = open("loginlock.txt", 'a') f.write(username + '\n') f.close() def userlogin(userinfo): count = 3 #计数器 flag = 'success' #标记登录状态 userid = 0 #标记用户编号 while True: username = input('please enter your name: ') if checklock(username) == 'lock': # continue break password = input('please enter your password: ') for i,user in enumerate(userinfo): if user['username'] == username and user['password'] == password: flag = 'success' break elif user['username'] == username and user['password'] != password: flag = 'fail' userid = int(i) break else: flag = 'nouser' if flag == 'success': print('login successful, welcome!') break elif flag == 'fail': # count -= 1 # print('who ', userinfo[userid]) failnum = int(userinfo[userid]['login_fail']) #统计登录失败次数 failnum -= 1 if userinfo[userid]['login_fail'] == 1: print('your account lock') userlock(userinfo[userid]['username']) sys.exit() else: userinfo[userid]['login_fail'] = failnum print('login fail, you have %s chance' % (failnum)) else: count -= 1 if count == 0: print('you login too much time') sys.exit() print('Sorry no user, you have %s chance' % (count)) if __name__ == '__main__': userinfo = [ {'username':'eric', 'password':'123456', 'login_fail':'3'}, {'username':'tom', 'password':'123456', 'login_fail':'3'}, {'username':'jerry', 'password':'123456', 'login_fail':'3'}, ] userlogin(userinfo)