Python作业

Day12 登录(simple)

2019-08-06  本文已影响0人  风月辞寒

代码:

"""
json内容:[{"user": "luoxi1", "pw": "123456", "students": [{"name": "xiaoming1", "sno": "001", "sex": "\u7537", "age": 12, "tel": "12312331233"}, {"name": "xiaoming2", "sno": "002", "sex": "\u7537", "age": 13, "tel": "12312331233"}, {"name": "xiaoming3", "sno": "003", "sex": "\u7537", "age": 14, "tel": "12312331233"}, {"name": "xiaoming4", "sno": "004", "sex": "\u7537", "age": 15, "tel": "12312331233"}]}, {"user": "luoxi2", "pw": "123456", "students": []}, {"user": "luoxi4", "pw": "123456", "students": []}, {"user": "luoxi3", "pw": "123456", "students": []}]
"""
"""______lxh______"""
import json


def index():
    with open('files/page.txt', encoding='utf-8') as f:        # 从文本文件中获取界面
        page = f.read()

    while True:
        print(page)
        choice = input('请输入:')
        if choice == '1':
            login()
        elif choice == '2':
            regist()
        elif choice == '0':
            break
        else:
            print('输入有误!')
            continue

def login():
    username = input('请输入用户名:')
    password = input('请输入密 码:')

    with open('files/users.json', encoding='utf-8') as f:   # 读取json文件中的用户
        content = f.read()
        users = json.loads(content)

    for n in users:
        if username == n['user']:       # 判断用户是否正确
            while password != n['pw']:      # 判断密码是否正确
                password = input('密码错误!\n请重新输入密码:')
        else:
            print('登录成功!')
            break
    else:
        print('用户不存在!')


def regist():
    username = input('请输入用户名(3~6)位:')

    with open('files/users.json', encoding='utf-8') as f:
        content = f.read()
        users = json.loads(content)

    while True:
        while not 3 <= len(username) <= 6:      # 判断用户名长度
            username = input('该用户名长度不正确!\n请输入用户名(3~6)位:')
        for n in users:
            if username == n['user']:       # 判断用户是否存在
                username = input('该用户已存在!\n请重新输入用户名(3~6)位:')
                break
        else:
            break

    password = input('请输入密码(6~12)位:')
    while not 6 <= len(password) <= 12:
        password = input('请重新输入(6~12)位的密码:')

    with open('files/users.json', 'w', encoding='utf-8') as f:      # 添加用户信息
        users.append({'user': username, 'pw': password, 'students': []})
        f.write(json.dumps(users))
        print('注册成功!')


if __name__ == '__main__':
    index()
上一篇下一篇

猜你喜欢

热点阅读