项目需求描述:要求用户输入用户名和密码,认证成功后显示欢迎信息,如果连续输错三次密码则锁定该用户。
逻辑流程图:
实现代码:
#!/usr/bin/env python import sys account_file = 'account.txt' lock_file = 'lock.txt' # put accounts in a list fh_account = open(account_file) account_list = fh_account.readlines() fh_account.close() # every account has 3 chances of attempt at the beginning retry_count = {} for line in account_list: line = line.split() retry_count[line[0]] = 3 while True: # put locked accounts in a list fh_lock = open(lock_file) lock_list = [] for i in fh_lock.readlines(): line = i.strip('\n') lock_list.append(line) fh_lock.close() # handle the username and password empty issue username = raw_input('Username: ').strip() if len(username) == 0: print '\033[31;1mUsername should not be empty !\033[0m' continue password = raw_input('Password: ').strip() if len(password) == 0: print '\033[31;1mPassword should not be empty !\033[0m' continue # authentication part if username in lock_list: print "\033[31;1mSorry, '%s' is locked already !\033[0m" % username continue if not retry_count.has_key(username): # inexistent account retry_count[username] = 3 for line in account_list: line = line.split() if username == line[0] and password == line[1]: # authentication pass retry_count[username] = 3 # reset retry times for this account sys.exit('\033[32;1mWelcome %s login my system !\033[0m' % username) else: # authentication failed print '\033[31;1mWrong username or password !\033[0m' retry_count[username] -= 1 if retry_count[username] > 0: print '\033[31;1mYou have %d more chances !\033[0m' % retry_count[username] else: # no more chance of attempt fh = open(lock_file, 'a') fh.write('%s\n' % username) fh.close() print "\033[31;1mSorry, '%s' is locked !\033[0m" % username