我显示一些与数字相关的文本选项,然后我想根据用户输入的数字执行一些功能。
第一个用户需要选择1或2,当用户选择1时工作正常。
但是当用户选择 2 时,我会要求用户选择其他选项,而当用户选择任何数字时,它总是显示选项不可用。
但我只想在用户选择不是 3、4、5 或 7 的数字时显示此消息。
您知道问题出在哪里以及如何解决这个逻辑吗?
def nav(number):
while True:
input = raw_input(number)
if input == "1":
upload()
return False
elif input == "2":
results = table.get()
# here I show the name of users from database
for r in results:
print r["name"]
print " 3 - Add user"
print " 4 - Edit user"
print " 5 - Remove user"
print " 7 - Exit"
nav("Select an option: ")
if input == "":
print "field is empty"
if input == "3":
addUser()
return False
if input == "4":
removeUser()
if input== "5":
editUser()
elif input== "7":
return False
else:
print "Option not available"
def main():
print " 1 - Users managment"
print " 2 - Upload Files"
print " 7 - Exit"
nav("Select an option: ")
main()
最佳答案
你应该有两个函数。一个要求您选择一个选项,一个解析该选项。例如:
def upload():
# does whatever upload does....
def user_mgmt():
def adduser():
"""Adds a new user"""
pass
def edituser():
"""Edits an existing user"""
pass
def deluser():
"""Deletes an existing user"""
pass
response_options = {'3': ('add user', adduser),
'4': ('edit user', edituser),
'5': ('remove user', deluser),
'7': ('exit', sys.exit)}
response_func = make_choice(response_options)
response_func()
def nav():
response_options = {'1': ('manage users', user_mgmt),
'2': ('upload', upload),
'7': ('exit', sys.exit)}
response_func = make_choice(response_options)
response_func()
def make_choice(optiontable):
for resp, msg_func in optiontable.items():
msg, _ = msg_func
print("{} - {}".format(resp, msg))
usr_resp = raw_input(">> ")
try:
result = optiontable[usr_resp][1]
except KeyError:
raise # let the caller handle it
return result
这实际上是collections.namedtuple
的一个非常好的用例
from collections import namedtuple
Choice = namedtuple("Choice", ['msg', 'callback'])
def nav():
response_options = {'1': Choice(msg="Add user", callback=adduser),
...}
result = make_choice(response_options)
if result is None:
# improper user input -- handle it
else:
result.callback()
def make_choice(optiontable):
for resp, choiceobj in optiontable.items():
print("{} - {}".format(resp, choiceobj.msg))
usr_resp = raw_input(">> ")
return optiontable.get(usr_resp, None)
关于python - 执行基本选项菜单系统时出现问题 - 总是收到消息 "Option not available",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30384712/