python-3.x - 为什么 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()
解决方案
您的代码中有两个错误:
- 您应该在每个循环结束时阅读用户的输入。
尝试在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()
- sort() 应该在
names
(列表)上执行,而不是entry
(元组)
推荐阅读
- react-native - 将 TWITTER_CONSUMER_KEY / SECRET 放入客户端以进行 oAuth1 Twitter 登录是否存在安全漏洞?
- shell - 从制表符分隔的文本文件中选择前两列,并用“_”字符替换
- django - 在顶部显示模型的第一篇文章
- windows - 通过单击按钮在 Microsoft Visual Studio(通用 Windows 应用程序)中显示另一个页面
- node.js - 如果第三个键为真,则比较 mongodb 文档的两个键
- python - 使用 Python 寻找两支球队之间的最佳匹配
- angular6 - 应用溢出:隐藏到 .mat-tab-body-content
- android - 使用 ConstraintLayout 的简单但复杂的布局
- salesforce - 无法从 SOQL 查询中的 createdDate 中提取年份
- marklogic - marklogic 中的 Cts 和 Xmdp 函数