基本选项菜单失败 - 需要帮助

Basic option menu is failing - help needed

我正在创建一个可以执行操作(新增、更新、删除、查找和退出)的基本电话簿程序。我有第一个选项作为添加条目,第二个选项作为删除条目。每次用户完成一个动作,select 一个动作的选项应该再次出现。当用户第二次 selects 时,它带回第一个项目而不是 selection;例如; 1是添加新联系人,2是删除新联系人。用户 selects 1,添加新联系人被要求 select 另一个选项,选择 2 但选项 1 的代码再次运行以添加新而不是删除。

print("Please select an option from the main menu :\n")

def print_menu():
    print("1 : Add New Entry")
    print("2 : Delete Entry")
    print("3 : Update Entry")
    print("4 : Lookup Number")
    print("5 : QUIT")
    print()

print_menu()

while 1 == 1:
    try:
        menuOption = int(input())
        break
    except:
        print("Invalid! Please choose an option between 1 and 5.")

while menuOption not in(1,2,3,4,5):
    print("Invalid! Please choose an option between 1 and 5.")
    try:
        menuOption = int(input())
        break
    except:
        print("Invalid! Please choose an option between 1 and 5.")

###the above works perfect to set menu and restrict entry

phonebook = {}

#while menuOption != 5:
    #menuOption = int(input("Enter your selection (1-5): "))

while 1 == 1 :

 if menuOption == 1: #
        print("\nNEW CONTACT")
        while True:
            name = input("Contact Name : ") 
            if name.replace(' ','').isalpha():
                break
            print('Please enter a valid name.')
        while True:
            try:
                number = int(input("Contact Number : "))
                if number:
                   break
            except:
                print("Please enter a valid number.")

        if number in phonebook:
            print("Contact already exists. Duplicates are not allowed.\n")
        else:
            phonebook[number] = name 
            print("Success! New contact has been added.\n")

            print("PLEASE SELECT AN OPTION BETWEEN 1 AND 5  \n")
            try:
                option = int(input())
            except:
                 print("Please enter a numeric value between 1 and 5  \n")        


    elif menuOption == 2: ##delete
        print("\nDELETE CONTACT") 
        name = input("Contact Name : ")
        if name in phonebook:
            del phonebook[name]
            print(name, "has been removed from your contacts.")
        else:
            print("Contact not found.")

        print("PLEASE SELECT AN OPTION BETWEEN 1 AND 5  \n")
        try:
            option = int(input())
        except:
            print("Please enter a numeric value between 1 and 5  \n")

您的代码检查 menuOption 的值,但输入 option。只需更改

option = int(input())

进入

menuOption = int(input())

欢迎来到堆栈,未雨绸缪!在查看 at/running 您的代码时,提醒用户在 1 到 5 之间输入的消息出现的次数比我预期的要多一些,以及您可能尚未编码的随机其他错误。我建议定义更多功能(用于菜单选项)并更多地构建您的代码将使您的代码更易于阅读和遵循。

下面(顺便说一句,它不完整或没有错误),我重新构建了您的代码,以便在调用 main() 时,Phone 书籍菜单选项显示,用户可以选择另一个选项。不用在各种函数之间使用 long "else-if"/elif ,而是将各种菜单例程整齐地组织在 main() 函数中的一个 while 语句中,并将选择组织到 5 个不同的函数中: add()/delete() 等(我将伪代码放入 update/lookup/exit fns)。我希望你觉得这有帮助。我确实发现,如果我在预期输入数字时输入字符串,则会抛出一条错误消息。我插入了评论以提供帮助。

希望这对您有所帮助

phonebook= []

def main():
    print("\n\tPhone Book") #title

# main menu
    print("\n\tMain Menu")
    print("\t1. Add a contact")
    print("\t2. Delete a contact")
    print("\t3. Update a contact")
    print("\t4. Look up")
    print("\t5. Quit")

    menuOption = int(input("\nPlease select one of the five options "))

    while menuOption not in(1,2,3,4,5)  :
        ## insert try/except error handling needed here to handle NaN ##
        print("\nPlease insert a numeric option between 1 and 5")
        menuOption =int(input())

    while menuOption <=5:
        mOpt =menuOption
        if menuOption == 1:
            Add(mOpt)
        elif menuOption == 2:
            Delete(mOpt)
        elif menuOption == 3:
            Update(mOpt)
        elif menuOption == 4:
            LookUp(mOpt)
        elif menuOption == 5:
            ExitPhone(mOpt)
        else:
           print("Invalid input! Please insert a value between 1 and 5")

# add contact
def Add(mOpt):
    ##Option 1
    add = ""
    contact = True

    print("\n\tADD CONTACT")

    while contact == True:
          if mOpt == 1: 
              print("\nNEW CONTACT")
              while True:
                 name = input("Contact Name : ") 
                 if name.replace(' ','').isalpha():
                    break
                 print('Please enter a valid name.')
              while True:
                  try:
                     number = int(input("Contact Number : "))
                     if number:
                          break
                  except:
                       print("Please enter a valid number.")

              if number in phonebook:
                 print("Contact already exists. Duplicates are not allowed.\n")
              else:
                 #item = name + number this won't be found in the delete function
                 phonebook.append(name)
                 phonebook.append(number)

                 #print(phonebook)
                 print("Success! New contact has been added.\n")

          add = input("Would you like to add another? Y (yes) or N (no)")
          add = add.lower()

          if add=="yes" or add=="y":
            contact = True
          else:
            contact = False
            main()

# delete
def Delete(mOpt):
    redel = ""
    delcontact = True

    print("\n\tDELETE CONTACT")

    while delcontact == True:
        if mOpt == 2:
            print("Enter Contact Name:")
            name = input("Contact Name : ")
            if name in phonebook:
              ## insert code here to find associated number 
              ## and concatenate it if you have created an 'item'
              phonebook.remove(name) #removes name, leaves the number
              print(name, "has been removed from your contacts.")
              #print(phonebook)
            else:
              print("Contact not found.")

        redel = input("Would you like to delete another? Y (yes) or N (no)")
        redel = redel.lower()

        if redel =="yes" or redel =="y":
            delcontact = False
        else:
            delcontact = True
            main()

def Update(mOpt):
  if mOpt == 3: 
      print("\nUpdate function")
      main()

def LookUp(mOpt):
   if mOpt == 4: 
      print("\nLookUp function")
      main()

def ExitPhone(mOpt):
  if mOpt == 5: 
    print ("Exit?")
    main()

main()