首页 > 解决方案 > 为什么 While 循环在我的程序中不起作用?

问题描述

任务是创建一个程序,允许用户输入朋友的姓名和电话号码,然后打印出按姓氏排序的联系人列表。还要使用函数。

我的问题是它只要求用户执行一项操作,然后立即询问详细信息。它应该要求用户选择另一个动作。退出、添加联系人、显示联系人或排序联系人。

def menu():
  '''Display Menu'''
  print(
    """

    Contact Lists

    0 - Exit
    1 - Show Contacts
    2 - Add Contacts
    3 - Sort Contacts
    """
    )

def ask():
  user = None
  user = input("Action: ")
  print()
  return user

def main():
  menu()
  action = ask()
  names = []

  while action != 0:
    if action == "0":
      print("Closing Contact Lists.")

    elif action == "1":
      print("Contact Lists: ")
      for name in names:
        print(name)
#setting a condition if user enter "2" it will let user add name, last name and phone number
    elif action == "2":
        name = input("Add contact's first name: ") #input 1
        last_name = input("Add contact's last name: ") #input 2
        contact_number = input("Add phone number for the contact name: ") #input 3
        entry = (last_name, name, contact_number)
        names.append(entry)

#setting a condition if user enter "3" it will sort contact list according to last names
    elif action == "3":
        entry.sort(reverse=True) #use of sort() to sort lists of by last names
        print(names)
    else:
        print("Invalid Action!") 

main()

标签: python-3.xfunctionsortingwhile-loop

解决方案


您的代码中有两个错误:

  1. 您应该在每个循环结束时阅读用户的输入。

尝试在action = ask()最后一个else条件下添加。

编辑

代码片段:


#setting a condition if user enter "3" it will sort contact list according to last names
    elif action == "3":
        entry.sort(reverse=True) #use of sort() to sort lists of by last names
        print(names)
    else:
        print("Invalid Action!") 
    action = ask()
  1. sort() 应该在names(列表)上执行,而不是entry(元组)

推荐阅读