我在让我的代码正确“返回”选项字符串之一时遇到问题。
如果用户第一次正确输入了其中一个字符串选项,那么在执行“while”到“if/elif”语句时,“return”值会完美返回。没问题。
但是,如果用户第一次没有正确输入数据,我会尝试用我最后的“else”语句来捕捉它,然后再次开始该函数。然而,第二次/第三次/等时间,即使用户输入了一个有效的选择,'return' 类型是 None 并且返回的值是 None。
所以,我的用户验证缺少一些东西。有什么想法吗?
#Global variable initialization
mainSelection = str(None)
#Santa's Christmas Card List Main Menu function
def XmasMainMenu(mainSelection):
print('')
print('How may the elves be of service today?')
print('')
print('\"PRINT\" - Print out the Christmas card list from the database.')
print('\"ADD\" - Add nice recipients information to the Christmas card list.')
print('\"SEARCH\" - Search the database for information.')
print('\"DELETE\" - Remove naughty recipients from the Christmas card list. ')
print('\"EXIT\" - Exit the program without any printing or changes to the database.')
print('')
mainSelection = input('Please enter your selection: ')
mainSelection = mainSelection.lower()
print(type(mainSelection), mainSelection)
#Selection return value
while mainSelection != None:
if mainSelection == 'print':
print('|| Will print out the Xmas Card List ||')
return mainSelection
elif mainSelection == 'add':
print('|| Will prompt user to add information to the DB ||')
return mainSelection
elif mainSelection == 'search':
print('|| Will prompt user to search the information in the DB ||')
return mainSelection
elif mainSelection == 'delete':
print('|| Will prompt the user to delete recipients from the DB ||')
return mainSelection
elif mainSelection == 'exit':
print('|| Will exit the user from the program with no changes')
return mainSelection
elif mainSelection == 'drop table':
print('|| Will call the XmasTableDrop function ||')
return mainSelection
else:
print('')
print('Input Error: Please enter a valid selection above!')
print('Try again...')
print('')
print(type(mainSelection), mainSelection)
break
XmasMainMenu(mainSelection)
第一个用户输入无效。收到错误消息,功能重新开始。第二个用户输入有效->但是,“返回”类型为无,值为无(这是我需要修复的,但无法弄清楚)。