第一周 模拟登陆、三级菜单


模拟登陆:
1、用户输入账号密码进行登陆
2.用户信息保存在文件中
3、用户密码输入错误三次后锁定用户
with open('userinfo',mode='w+',encoding='utf-8')as f:
    f.write('1251865477\n123456')

i=0
li=[]
while i<3:
    username =input('请输入你的账号:')
    password =input('请输入你的密码:')
    with open('userinfo', mode='r+', encoding='utf-8')as f:
        for line in f:
            li.append(line)

    if username.strip() == li[0].strip() and password == li[1].strip():
        print('登陆成功')
        break
    else:
        print('用户名或密码错误,请重试')
    i+=1

else:
    print('用户密码输入错误三次,账号已锁定')
三级菜单:
1、运行程序输出第一级菜单
2、选择第一菜单某项,输出二级菜单,同理输出三级菜单
3、菜单数据保存在文件中
4、让用户选择是否要退出
5、有返回上一级菜单功能
ps:用到字典、列表,while循环

menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车站':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
}
with open('data',mode='r+',encoding='utf-8')as f:
    a=f.read()
    # print(a,type(a))
    menu=eval(a) #str转化为dic
    print(menu)
# 1)

current_level =menu
parent_level=[] #保存所有父集,最后一个元素永远是父级

while True:
    for key in current_level:
        print(key) #展示 北京、上海、山东

    choice= input('>>>') #用户输入 第一层
    if choice in current_level:
        parent_level.append(current_level) #在进入下一级之前,把当前层的父集保存下来
        current_level=current_level[choice] #改成子层 继续while循环

    elif choice=='b': #返回上一级
        if parent_level: #如果父集不为空
            current_level=parent_level.pop()  # 删掉最后一个元素,并将值返回current_level循环
    elif choice =='q':
        break
    else:
        print('输入有误')
# 2)
def three_menu(dic):
    while 1:
        for k in dic.keys():
            print(k)     #北京 上海 山东

        key = input('>>>').strip() #北京

        if key =='b' or key == 'q': #b为返回上一级、q为退出
            return key
        elif key in dic.keys() and dic[key]:

            ret = three_menu(dic[key])
            if ret == 'q':
                return 'q'

        elif (not dic.get(key,'没有这个地区')) or (not dic[key]):
            continue


three_menu(menu)
原文地址:https://www.cnblogs.com/hanfe1/p/10643921.html