使用字典实现用户账号管理

db={}#声明一个空的字典
def newuser():
    prompt='请输入注册账号:'
    while True:
        name=input(prompt)
        #检测字典中是否已经存在键为用户注册账号的元素
        if name in db:
            prompt='账号已存在,请重新输入:'
            continue
        else:
            password=input('请输入密码:')
        #将用户注册的账号密码作为字典的键值对
            db[name]=password
            break
def olduser():
    name=input('请输入登录账号:')
    password=input('请输入密码:')
    #获取注册账号所对应的密码
    userpwd=db.get(name)
    #判断用户输入的登录密码与注册密码是否一致
    if userpwd==password:
        print('欢迎登录:'+name)
    else:
        print('登录名或密码错误,请重新登录!')
def showmenu():
    prompt='请输入用户状态(n:注册/e:登录):'
    con=False
    while not con:
        chosen=False
        while not chosen:
            try:
                #将用户输入的字母小写格式化
                choice=input(prompt).strip()[0].lower()
            except(EOFError,KeyboardInterrupt):
                choice='q'
            print('你按下了[%s]键'%choice)
            if choice not in 'neq':
                print('你输入的字符不合法,请重新输入')
            else:
                chosen=True
                con=True
        if choice=='n':
            newuser()
        elif choice=='e':
            olduser()
        else:
            showmenu()                               
        showmenu()    

效果如下:

猜你喜欢

转载自blog.csdn.net/menghu_bit/article/details/81391897
今日推荐