刷题 - Login 连续输入三次锁定

Login 连续输入三次锁定

需求解析:

用户输入用户名密码之后,和文件中数据进行比对,如果用户不存在即跑错,如果用户连续输入3次错误即锁定。

此题运用python字典,python文件处理,while,for语句,以及正则表达式。其中字典需和string相互转换完成存储。

文件为txt,内容如下  

user:alice  password:123  failcount:2

user:alex  password:265  failcount:1

user:eric  password:654  failcount:3

流程:

先get 文件信息将string转为dict,username为dict key

用户输入用户名和密码之后和dict中key进行比对

如果不存在则报错退出本次循环,继续循环

如果存在,查看failcount

  如果大于等于3,报错返回继续进循环

  如果小于三,对比password

    如果password正确,提示welcome结束运行

    如果password错误,报错返回继续循环

  

 

Code:

def getUserInfo(filename):
    f1 = open(filename, 'r+')
    f1_context = f1.readlines()
    global user_info_dict
    user_info_dict = {}
    for each_user in f1_context:
        user_data_tup = re.findall(r'(\w+):(\w+)\s?', each_user)
        user_data_dict = {}
        for i in user_data_tup:
            user_data_dict[i[0]] = i[1]
            user_info_dict[user_data_dict['user']] = user_data_dict
    f1.close()

def putUserInfo(filename):
    f1 = open(filename, 'r+')
    f1.truncate()
    f1.close()
    for userInfo in user_info_dict.values():
        for key, value in userInfo.items():
            f1 = open(filename, 'a')
            a = '%s:%s ' % (key, value)
            f1.write(a)
            f1.close()
        f1 = open(filename, 'a')
        f1.write('\r\n')
        f1.close()

def userExist(username):
    if username in user_info_dict:
        return True
    else:
        print('Invalid username or password!')
        return False

def userLocked(username):
    if int(user_info_dict[username]['failcount']) >= 3:
        print('Your account has been locked, please contact admin!')
        return True
    else:
        return False

def passwordExpected(username, password):
    if user_info_dict[username]['password'] == password:
        print(username + ', welcome!')
        user_info_dict[username]['failcount'] = '0'
        return True
    else:
        print('Invalid username or password!')
        return False

def onPasswordError(username):
    fc = int(user_info_dict[username]['failcount'])
    fc += 1
    user_info_dict[username]['failcount'] = str(fc)
    if fc >= 3:
        print('Your account has been locked, please contact admin!')

if __name__ == '__main__':
    import re
    getUserInfo('F1.txt')
    success = None
    while not success:
        username = input('Username:')
        password = input('Password:')
        if userExist(username):
            if not userLocked(username):
                if passwordExpected(username, password):
                    success = True
                    putUserInfo('F1.txt')
                else:
                    onPasswordError(username)
                    putUserInfo('F1.txt')
 

  



posted @ 2020-05-03 09:29  Alice0708  阅读(153)  评论(0编辑  收藏  举报