一个简单的三级菜单
#! /usr/bin/env python #-*- coding:utf-8 -*- mymenu = { '动物' : { '猫' : ['黄猫','花猫'], '狗' : ['二哈','金毛'] }, '植物' : { '树' : ['大树','小树'], '草' : ['绿草','矮草'] } } menu_list = list(mymenu.keys()) while True: print(" 编号 ".center(50,'*')) for i in menu_list: print(menu_list.index(i)+1,i) a_id = input("请输入菜单编号,或输入q(quit)退出:") if a_id.isdigit(): a_id = int(a_id) if a_id > 0 and a_id <= len(menu_list): a_name = menu_list[a_id-1] b_list = list(mymenu[a_name].keys()) while True: print(" B级 ".center(50,'*')) for v in b_list: print(b_list.index(v)+1,v) b_id = input("请输入编号,或输入b(back)返回上级菜单,或输入q(quit)退出:") if b_id.isdigit(): b_id = int(b_id) if b_id > 0 and b_id <= len(b_list): city_name = b_list[b_id-1] town_list = mymenu[a_name][city_name] while True: print(" C级 ".center(50,'*')) for j in town_list: print(town_list.index(j)+1,j) back_or_quit = input("输入b(back)返回上级菜单,或输入q(quit)退出:") if back_or_quit == 'b': break #终止此层while循环,跳转到上一层While。 elif back_or_quit == 'q': exit() else: print("输入非法!") else: print("编号%d不存在。"%b_id) elif b_id == 'b': break elif b_id == 'q': # flag = True # break exit() else: print("输入非法!") # if flag1: # break else: print("编号%d不存在。"%a_id) elif a_id == 'q': break else: print("输入非法!")