python - 执行基本选项菜单系统时出现问题 - 总是收到消息 "Option not available"

标签 python

我显示一些与数字相关的文本选项,然后我想根据用户输入的数字执行一些功能。

第一个用户需要选择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/

相关文章:

python - 数据框中字典列的列表

python - scrapy python将start_urls从spider传递到管道

python - 如何检查 csv.DictReader 对象是否为空

python - 谷歌应用引擎: Devserver is hideously slow

python - 如何结合使用 mongoengine 的 operator all 和 icontains

python - 将嵌套列表逐列写入 CSV

python - 从系列字典创建 Pandas 数据框

python - 插入特定于列的 NaN 并根据值删除行

python - 同时使用类函数和静态方法? (Python)

python - 子图边距以适合 matplotlib 中的标题和标签