python 第二周作业

二.周末综合作业:

编写用户登录接口

① 输入账号密码完成验证,验证通过后输出"登录成功"
② 可以登录不同的用户
③ 同一账号输错三次锁定,(提示:锁定的用户存入文件中,这样才能保证程序关闭后,该用户仍然被锁定)

import json

with open('user_db', 'r') as f:
    user_dict = json.load(f)  # {"alex": '123', "egon": '123', 'blacklist': []}

count = 0
while True:
    name = input('输入账号:').strip()
    pwd = input('输入密码:').strip()
    if name in user_dict:
        if pwd == user_dict[name]:
            if name not in user_dict['blacklist']:
                print('登陆成功')
                break
            else:
                print('该账号以被锁定')
                break
        else:
            count += 1
            print('密码错误%s次' % count)
            if count == 3:
                print('密码已经输错三次 被锁定')
                with open('user_db', 'w') as f:
                    user_dict['blacklist'].append(name)
                    json.dump(user_dict, f)
    else:
        print('账号不存在')

2.编写程序实现用户注册后,可以登录

while True:
    msg = """
退出
登录
注册
        """
    print(msg)
    cmd = input('请输入命令编号>>: ').strip()
    if not cmd.isdigit():
        print('必须输入命令编号的数字,傻叉')
        continue

    if cmd == '0':
        print("已退出程序!")
        break
    elif cmd == '1':
        # 登录功能代码(附加:可以把之前的循环嵌套,三次输错退出引入过来)
        count = 0
        while count < 3:
            user = input("请输入用户名:")
            psd = input("请输入密码:")
            with open("name.txt", mode="r", encoding="utf-8") as f:
                for line in f:
                    #  user_data = alex:'123'
                    username, password = line.strip().split(":")
                    if user == username and password == psd:
                        print("登录成功")
                        break
                else:
                    count += 1
                    print('您已输错%s次,还剩%s次' % (count, 3 - count))
        else:
            print('输错3次,退出程序')
posted @ 2020-03-13 22:38  nick_xm  阅读(157)  评论(0编辑  收藏  举报