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

时间:2019-02-12 22:36:29

标签: python python-3.x phonebook

我正在创建一个基本的电话簿程序,该程序可以执行操作(添加,更新,删除,查找和退出)。我有第一个选项作为添加条目,第二个选项作为删除条目。每次用户完成一个动作时,都会出现再次选择一个动作的选项。当用户第二次选择时,它返回到第一项而不是选择。例如; 1是添加新联系人,2是删除新联系人。用户选择1,添加新联系人被要求选择另一个选项,选择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")

2 个答案:

答案 0 :(得分:1)

欢迎来到堆栈,雨天!在查看/运行您的代码时,提示用户输入一到五个的消息比我预期的要多,还有可能还没有编码的其他随机错误。我建议定义更多功能(用于菜单选项)并更多地组织代码,这将使您的代码更易于阅读和遵循。

在下面(不完整或没有错误),我重新组织了代码,以便在调用main()时显示“电话簿”菜单选项,并且用户可以选择另一个选项。代替在各种功能之间使用长的“ else-if” / elif,在while函数中的一个main()语句中巧妙地组织了各种菜单例程,并将选项组织成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()

答案 1 :(得分:0)

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

option = int(input())

进入

menuOption = int(input())