day1 job 2: multi-level menu operation

Posted by joon on Tue, 02 Jul 2019 00:26:08 +0200

Assignment 2: Multilevel menu

(1) Three-level menu

(2) You can choose to enter each sub-menu at the next time.

(3) Necessary New Knowledge Points: Lists, Dictionaries

Requirements: Input b returns to the upper level, input q exits the whole program


Thought: The first level of the three-level menu is province, the second level is city, and the third level is county. Users can choose what they want to see according to the content. Therefore, to use the while cycle to operate, there must be two levels of cycle. The first level is b-responsible, the second level is q-responsible. If you want to quit the whole cycle, input Q to end the whole cycle. Input B ends the inner loop, and after jumping out of the inner loop, the following loop will continue to execute.

The flow chart is as follows:


Above is a general flow chart of the program:


(1) First of all, we should have a dictionary to store three-level menus.

(2) Display the content of the first-level menu;

(3) The user enters the contents of the first-level menu for viewing;

(4) Display the content of the second-level menu;

(5) User input to view secondary menu content

(6) Display three-level menu content;

(7) Users view the corresponding contents of the three-level menu.

The code is as follows:


import collections
#Import collections for importing ordered Dictionaries
dic = collections.OrderedDict()
#Ordered dictionary
dic["Henan"] = {
    "Nanyang":["Dengzhou","Nanzhao","Xixia","Tongbai","Newfield","Fangcheng","Zhenping","wancheng district"],
    "Luoyang":["Old Town","Mengjin County","Yiyang County","Yichuan County","Luoning County","Luanchuan County","Luolong District"],
dic["Hunan"] = {
    "Changsha":["kaifu district","Wangcheng District","Yuelu District","furong district","Ningxiang County","Tianxin District","Xingsha"],
    "Loudi":["Lianyuan","Shuangfeng","Lengshuijiang City"],

dic["Guangdong"] = {
    "Guangzhou":["Yuexiu District","Huadu District","Tianhe District","Zengcheng District"],
    "Shenzhen":["luohu district","Futian District","Baoan District","Yantian district","longgang district","Longhua District","Pingshan District"],

active = True
d1 = collections.OrderedDict()
#Define an empty dictionary where the user stores first-level menu content
d2 = collections.OrderedDict()
#Define an empty ordered dictionary for storing secondary menus
d3 = []
#Define an empty list for storing three-level menus
while active:
    #Enter Level 1 Menu
    print("The name of a province.")
    for index1,province in enumerate(dic.keys(),1):
        print("  %s        %s  "%(index1,province))
        d1[index1] = province
        #Put the province number and its corresponding name in the dictionary.
    num1 = input("Please enter the province number you want to see:")
    if num1.isdigit():
        #Determine whether user input is a digital number
        if int(num1) > len(d1) or int(num1) < 1:
            print("Sorry, the number you entered is incorrect. Please re-enter it.")
        if num1 == "q":
            active = False
            print("You did not enter a number, please enter the correct number!")
    while active:
        #Type in Level 2 Menu
        print("The name of the city.")
        for index2,city in enumerate(dic[d1[int(num1)]].keys(),1):
            print("  %s        %s  " % (index2, city))
            d2[index2] = city
        num2 = input("Please enter the number of the city you want to see:")
        if num2.isdigit():
            if int(num2) > len(d2) or int(num2) < 1:
                print("The number of the city you entered is incorrect. Please re-enter it!")
                print(d1[int(num1)],"      ",d2[int(num2)])
            if num2 == "b":
                #If the user enters b to exit the current loop, call it to the previous loop
            elif num2 == "q":
                active = False
                print("The number you entered is incorrect. Please enter the correct number.")
        while active:
            #Enter the three-level menu
            print("County Number    Names of counties and districts")
            d3 = dic[d1[int(num1)]][d2[int(num2)]]
            for index3,place in enumerate(d3,1):
                print("  %s        %s  " % (index3, place))
            num3 = input("Please enter the county you want to inquire about./Area number:")
            if num3.isdigit():
                #Determine whether the string entered by the user is in digital format
                if int(num3) > len(d3) or int(num3) < 1:
                    print("The inquiry number you entered exceeds the range, please re-enter it!")
                    print(d1[int(num1)], "      ", d2[int(num2)],"      ",d3[int(num3)-1])
                if num3 == "b":
                elif num3 == "q":
                    active = False
                    print("The inquiry number format you entered is incorrect. Please re-enter it!")


In the code above, we have three menus and three loops. Each loop corresponds to the corresponding menu. It can terminate its own cycle and all loops of the system in its own loop. In addition, we often use input() to input numbers. In this case, we input character words. The letter "b" and the character number, if not judged, will cause the operation, because the character alphabet format can not be int(). Therefore, we first determine whether the user input is a number.


import sys

account_file = "user_file"
locked_file = "lock_file"

def deny_account(username):
    print("Your user has been locked in!")
    with open(locked_file,"a") as deny_f:
        deny_f.write("\n" + username)

def main():
    retry_count = 0
    retry_limit = 3
    while retry_count < retry_limit:
        username = input("\033[32:lm enter one user name:\033[om")
        with open(locked_file,"r") as lock_f:
            #Use with file opening to prevent forgetting f.close() to close files
            lines = []
            for line in lock_f.readlines():
            if username in lines:
            for line in lock_f.readlines():
                if len(line) == 0:
                if username == line.strip():
                    sys.exit("\033[32:lm user %s It's locked!\033[0m" %username)

if __name__ == "__main__":

Topics: Delphi