一.需求分析
三级目录要能够实现以下要求:
- 显示根目录,任何子目录中都可以通过输入b字符来返回根目录
- 任何子目录中都可以通过输入q字符来返回上一级目录
- 主目录进入子目录后,系统能够打印子目录,根据指打印信息进入下级目录或者返回
二.代码实现
# 定义字典包括,国家,州(省),市 dic = {'中国': {'河北': ('石家庄', '邢台', '衡水',), '北京': ('昌平', '海淀', '朝阳',), '山西': ('太原', '大同', '运城',)}, '美国': {'纽约州': ('纽约市', '罗彻斯特', '水牛城',), '加利福利亚州': ('洛杉矶', '好莱坞', '阿罕布拉',), '宾夕法尼亚州': ('费城', '伯利恒', '华盛顿',)}, '澳大利亚': {'维多利亚州': ('墨尔本', '吉朗', '巴里迪',), '西澳大利亚州': ('马扎尔', '柏斯', '费里曼图',), '南澳大利亚州': ('阿德莱德', '内陆', '巴罗莎'), }} # print(dic['中国']['河北']) dic_dir = {1: "中国", 2: "美国", 3: "澳大利亚", } # 定义国家跟序号的对应关系 dic_dirCity = {1: ("河北", "北京", "山西"), 2: ("纽约州", "加利福利亚州", "宾夕法尼亚州",), 3: ("维多利亚州", "西澳大利亚州","南澳大利亚州",) }# 省(州)对应关系 def Directory():#定义三级目录函数 DirectoryPos = 0#记录当前目录位置 while True: if DirectoryPos == 0: for temp in dic_dir: print(temp,":",dic_dir[temp])#打印根目录 getCountry= int(input("Please Chonse The Country:"))#输入字符转换成int类型变量 while getCountry<1 or getCountry>3:#合法性判断 getCountry = int(input("Input Error Please Reinput:")) DirectoryPos +=1 if DirectoryPos == 1: num = 0 for temp in dic_dirCity[getCountry]: num += 1 print(num,":",temp)#打印子目录 getProvince = input("Please Chonse The Province Inupt q Is Return Input b Back To Main:") if getProvince == 'q' or getProvince == 'b':#条件判断,进入下级目录或者返回 DirectoryPos -= 1 else: DirectoryPos += 1 getProvince = int(getProvince) if DirectoryPos == 2: for temp in dic[dic_dir[getCountry]] [dic_dirCity[getCountry][getProvince-1]]:#打印子目录 print(temp) getNum = input("Input q Is Return Input b Is Back To Main:") if getNum == 'q':#条件判断 DirectoryPos -= 1 if getNum == 'b': DirectoryPos =0 # print("The Game Is Over !") Directory()
程序运行结果图如下:
此程序没有特别运行条件,只要复制黏贴到PyCharm3.0以上的版本下即可使用,不支持PyCharm3.0以下的版本,此程序在输入条件的合法性判断上有bug由于时间原因暂不处理,后期如有时间会及时更新,有兴趣的朋友也可以自己改一下试试。