python - 基本选项菜单失败 - 需要帮助
问题描述
我正在创建一个可以执行操作(添加新、更新、删除、查找和退出)的基本电话簿程序。我有第一个选项作为添加条目,第二个选项作为删除条目。每次用户完成一个动作时,都会出现再次选择动作的选项。当用户第二次选择时,它会带回第一项而不是选择;例如; 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")
解决方案
欢迎来到堆栈,下雨天!在查看/运行您的代码时,提醒用户输入 1 到 5 的消息出现的次数比我预期的要多,以及您可能尚未编码的随机其他错误。我建议定义更多功能(用于菜单选项)并更多地构建代码将使您的代码更易于阅读和遵循。
下面(顺便说一句,这不完整或没有错误),我重新构建了您的代码,以便在main()
调用时,电话簿菜单选项显示并且用户可以选择另一个选项。代替在各个函数之间使用长长的“else-if”/elif ,各种菜单例程被整齐地组织在函数中的一个while
语句中,main()
并且选项被组织成 5 个不同的函数:add()
/delete()
等等。(我将虚拟代码放入更新/查找/退出 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()
推荐阅读
- java - Android Studio 中的 IDE 更新失败
- python - 如何将 x 轴移动 1 以从 1 而不是 0 开始?
- html - 仅 CSS 粘性菜单
- c++ - 为什么可以声明一个大小不是 const 或 constexpr 的 C++ 数组(在堆栈上)?
- r - R dplyr 查询不使用 PostgreSQL 中的表索引?
- javascript - 为什么javascript不做其他事情?
- web-scraping - 用于从雅虎财经中抓取股票代码的 Python 代码
- javascript - 在对象文字内分配数值不会引发任何错误
- android - 如何解决这个错误 E / libprocessgroup: set_timerslack_ns write error: Operation not allowed?
- android - Firebase 分析可打包数组不支持 API 28/29