Home Backend Development Python Tutorial Python writes a three-level while loop menu example

Python writes a three-level while loop menu example

Jul 17, 2017 pm 05:45 PM
python while cycle

下面这篇文章介绍python是如何编写一个三级while的循环菜单的

1.定义字典,字典里面嵌套字典,内嵌字典的值为列表。

思路:

<strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>湖北省的市:字典中的</span></strong><br><strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>定义3个字典,用于存储</span></strong><br><br><strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>{序列-键:市名}</span></strong>
Copy after login
shiqu_dir = {}
Copy after login
{序列-键:县}
Copy after login
xian_dir ={}
Copy after login
{序列-键:街道}
Copy after login
jiedao_dir = {}
Copy after login
函数将序列和键一一对应。
Copy after login
<strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>for number,key in enumerate(Hbei_map.keys())  获取序列键和市名存储到 市名字典</span></strong><br><br><strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>用一个列表 chose = [] 来存储所选择的市--县程-街道</span></strong>
Copy after login
<strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>chose[0],chose[1],chose[2]最后使用切片返回</span></strong><br><br><strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>中间输入全部使用的判断方式for循环: for k,v in xxx.items():</span></strong><br><strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>                     if input == k:</span></strong><br><strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>让用户只能输入序列中的数字。使用判断语句:</span></strong>
Copy after login
<strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>  if int(input) not in 字典.keys():</span></strong><br><strong><span style='font-family: "Microsoft YaHei"; font-size: 14px'>      print("您输入了非法的序列,请输入一下序列 {}".format(shiqu_list))</span></strong><br><br>
Copy after login
# -*- coding: utf-8 -*-__author__ = 'hujianli'import sys
Hbei_map = {"武汉市":{"江岸区":["上海街","大智街","一元街","车站街","四唯街","永清街","球场街","西马街","台北街","劳动街","花桥街","后湖街","谌家矶街"],         "硚口区":["易家墩街道","韩家墩街道","宗关街道","汉水桥街道","宝丰街道","荣华街道","崇仁街道","汉中街道"],         "武昌区":["积玉桥街道","杨园街道","徐家棚街道","新河街道"]
    },"荆州市":{"沙市区":["黄石港","崇文街道","解放路街道"],"荆州区":["城南街道","西城街道","东城街道","马山镇","川店镇"],"松滋市":["新江口镇","南海镇","八宝镇","陈店镇"],"公安县":["斗湖堤镇","埠河镇","杨家厂镇","斑竹垱镇"],"监利县":["容城镇","白螺镇","朱河镇"]

    },"孝感市":{"孝南区":["肖港镇","书院街道","车站街道","新华街道"],"应城市":["城中街道","城北街道","杨河镇","三合镇"],"安陆市":["李店镇","巡店镇","雷公镇","陈店乡"],

    },
}# print(Hbei_map["孝感市"]["应城市"])shiqu_dir = {}
xian_dir ={}
jiedao_dir = {}def jiance(name):if len(name) == 0:
        sys.exit("\033[31;1m选择不能为空,清重新输入~~\033[0m")elif shiqu == "quit" or shiqu == "exit":
        sys.exit("\033[31;1m 退出程序,三级菜单退出~~ \033[0m")else:return Trueprint("==============================================================================================================")print("湖北省下面的市区如下: ")for number,key in enumerate(Hbei_map.keys()):print(str(number+1) + ": " + str(key))
    shiqu_dir[number+1] = key

chose = []
shiqu_list = [x+1 for x in range(len(shiqu_dir.keys()))]while True:print("==========================================================================================================")
    shiqu = input("请输入您要查询的市区所对应的序列号,输入exit或者quit自动会退出.:")
    jiance(shiqu)if int(shiqu) not in shiqu_dir.keys():print("您输入了非法的序列,请输入一下序列 {}".format(shiqu_list))else:for keys,vlaue in shiqu_dir.items():if int(shiqu) == keys:
                chose = []
                chose.append(vlaue)print("================================================================================================")print("该市区下面的县级市或者片区域,县城列表如下:")for number,keys_xian in enumerate(Hbei_map[vlaue].keys()):print(str(number+1)+ ":" + str(keys_xian))
                    xian_dir[number+1] = keys_xianwhile True:print("=============================================================================================")
                    xian = input("请输入要查询的县城所对应的序列号,quit/exit退出: ")
                    jiance(xian)
                    xian_list = [x+1 for x in range(len(xian_dir.keys()))]if int(xian) not in xian_dir.keys():                         print("您输入了非法的序列,请输入一下序列 {}".format(xian_list))else:for k,v in xian_dir.items():if int(xian) == k:
                                chose.append(v)

                        jiedao_li = Hbei_map[chose[0]][chose[1]]for k,v in enumerate(jiedao_li):print(str(k+1) + ": " + str(v))
                            jiedao_dir[k+1] = vwhile True:print("=====================================================================================")
                            jiedao = input("请输入街道所对应的序列号 退出请输入quit/exit: ")
                            jiance(jiedao)
                            jiedao_list = [x+1 for x in range(len(jiedao_dir.keys()))]if int(jiedao) not in jiedao_dir.keys():print("您输入了非法的序列,请输入一下序列 {}".format(jiedao_list))else:for k,v in jiedao_dir.items():if int(jiedao) == k:
                                        chose.append(v)print("=================================================================================")print("\033[35;1m你选择的市:%s 县城是:%s 街道是:%s\033[0m"%(chose[0],chose[1],chose[2]))print("===================================================================================")breakbreakbreak
Copy after login

The above is the detailed content of Python writes a three-level while loop menu example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles