Python基础-02
本节内容:
1、 三级菜单
2、 字符编码
一、 三级菜单
#要求 1。可以一层一层进入到所有层
# 2。可以在每一层返回上一层
# 3.可以在任意层退出主菜单
# 4.写重复代码写成不重复
无脑版(单纯按照思路一步一步写)
back_flag = False exit_flag = False while not back_flag and not exit_flag: for key in manu:#打印第一层 (循环第一层) print(key) choice = input(">>:").strip() if choice == "q": exit_flag = True if choice in manu:#打印第二层 while not back_flag and not exit_flag:#让程序停留在第二层 for key2 in manu[choice]: print(key2) choice2 = input(">>:").strip() if choice2 == "b": back_flag = True if choice2 == "q": back_flag = True if choice2 in manu[choice]: while not back_flag and not exit_flag:#False for key3 in manu[choice][choice2]: print(key3) choice3 = input("3>>:").strip() if choice3 == "b": back_flag = True if choice3 == "q": exit_flag = True if choice3 in manu[choice][choice2]: while not back_flag and not exit_flag: for key4 in manu[choice][choice2][choice3]: print(key4) choice4 = input("4>>:").strip() print("last level") if choice4 == "b": back_flag=True if choice4 == "q": exit_flag=True else: back_flag = False else: back_flag = False else: back_flag = False
减少重复代码实现三级菜单
menu = { '北京':{ '朝阳':{ '国贸':{ 'CICC':{}, 'HP': {}, '渣打银行': {}, 'CCTV': {}, }, '望京':{ '优衣库':{}, 'apple': {}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '阿泰包子':{}, }, '天通苑': { '链家':{}, '我爱我家':{}, }, '回龙观':{}, }, '海淀':{ '五道口':{ '谷歌':{}, '网易':{}, 'Sohu':{}, 'Sogo':{}, '快手': {}, }, '中关村':{ 'Youku':{}, "Iqiyi":{}, "汽车之家": {}, "新东方": {}, "QQ": {}, }, }, }, '上海':{ "浦东":{ "陆家嘴":{ "CICC":{}, "高盛": {}, "摩根": {}, }, "外滩":{} }, "闵行":{}, "静安":{}, }, '山东':{ "济南":{}, "德州":{ "乐陵":{ "丁务镇":{}, "城区":{} }, "平原":{} }, "青岛": {}, }, } current_layer = menu #实现动态循环 # parent_layer = menu parent_layers = []#保持所以父级 ,最后一个元素永远都 是父亲级 while True: for key in current_layer: print(key) choice = input(">>>:").strip() if len(choice) == 0:continue if choice in current_layer:#改之前相当于父亲 parent_layers.append(current_layer)#在进入下一层之前,把当前层追加到父级 #下一次loop 当用户选择b的选择,就可以直接取列表的最后一个值出来就ok了 current_layer = current_layer[choice]#改成了子层 elif choice == "b": # current_layer = parent_layer if parent_layers:#判断是否为空 current_layer = parent_layers.pop()#取出列表最后一个值,因为他就是当前的父值 else: print("无此项")
二、 字符编码
二进制 ---》ASCII:智能存英文和拉丁字符,一个字符占一个字节:8位
in python2 # 默认是 ASCII
#in py3 #默认是 unicode #encode 在编码的同时,会把数据转成bytes类型 #decode 在解码的同时会把bytes类型转成字符串 #b = byte = 字节类型 =【0-255】
例程
s = '特斯拉' s_to_gbk = s.encode('gbk') print(s) print(s_to_gbk)