Python之简单的用户名密码验证

题目要求:

输入用户名密码
认证成功后显示欢迎信息
输错三次后锁定
 
#要求使用文件存储用户名和密码,每次从文件读入用户名和密码用来验证,如果输错三次密码该账户会被锁定,并讲锁定的用户名写入文件
#账号密码正确输出欢迎信息
 
涉及知识点:
文件读写操作
循环流程
程序判断流程
经过分析构思
我写的第一版代码如下:
#Author jack
# _*_ coding: utf-8 _*_
#date   2019-08-14
'''
作业一:编写登录接口
    输入用户名密码
    认证成功后显示欢迎信息
    输错三次后锁定
'''
#判断用户账号密码                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
def check_pass(username, password):
    with open('userfile.txt', 'r+') as f:
        content = f.readlines()
    for i in content:
        if i.split(',')[0] == username and i.split(',')[1].strip('\n') == password:
            return True
            break
    else:
        return False

#判断用户名是否锁定:
def isLock(username):
    with open('locklist.txt', 'r') as f:
        cont = f.read()
    if username in cont:
        return False
    else:
        return True

#写锁定用户名到locklist,如果用户输错三次,就调用此函数,讲锁定的用户名写入此文件
def writeErrlist(username):
    with open('locklist.txt', 'a+') as f:
        f.write(username)
        f.write('\n')

def main():
    count = 0   #存储输密码次数
    while count < 3:
        username = input('Please input your username: ')
        is_lock = isLock(username)
        if is_lock:
            passwd = input('Please input your password: ')
            result = check_pass(username, passwd)
            if result:
                print('welcome back! "{}"'.format(username))
                break
            else:
                count += 1
                if count < 3:
                    print('Invalid username or password, Please try again!')
                else:
                    print('Too many attempts, Your account has benn locked.')
                    writeErrlist(username)
        else:
            print('Your account has been locked!!!')                

if __name__ == "__main__":
    main()

  

posted @ 2019-08-14 21:45  jack-kaller  阅读(3550)  评论(0编辑  收藏  举报