简体   繁体   English

Python切换器无法访问

[英]Python Switcher Unreachable

I'm trying to make a simple dictionary mapping but I'm getting an error stating that switcher is unreachable. 我正在尝试制作一个简单的字典映射,但我收到一条错误,指出switcher无法访问。

def option_select(option):
    switcher = {
        1: "Option One",
        2: "Option Two",
        3: "Option Three",
        4: "Option Four",
        0: sys.exit()
    }
    return switcher.get(option, "Invalid choice")


print("Please select an option:")
print("1: Add a new student.")
print("2: Delete an existing student.")
print("3: List all students.")
print("4: Search for a student.")
print("0: Exit")
optionChoice = int(input("Selection: "))

option_select(optionChoice)

The definition of switcher will execute sys.exit() and your program will end. switcher的定义将执行sys.exit() ,您的程序将结束。

Your use of switcher is not a switch statement; 您对switcher使用不是开关声明; it is a dictionary, in which you map the key 0 to the return value of sys.exit() . 它是一个字典,您可以将键0映射到sys.exit()的返回值。 In order to determine this value and create the dictionary, sys.exit() is executed. 为了确定该值并创建字典,执行sys.exit() sys.exit() exits your program. sys.exit()退出程序。

The easiest fix is just to deal with exit separately: 最简单的解决方法是单独处理退出:

def option_select(option):
    if option==0:
        sys.exit()
    switcher = {
        1: "Option One",
        2: "Option Two",
        3: "Option Three",
        4: "Option Four",
    }
    return switcher.get(option, "Invalid choice")

Or you could write your switcher so that each value is callable: 或者你可以编写你的switcher以便每个值都可以调用:

switcher = {
    1: add_student,
    2: delete_student,
    3: list_students,
    4: search_students,
    0: sys.exit,
}

and define the values as functions, and then you can call the result you get from the dictionary to do whatever it is supposed to do. 并将值定义为函数,然后您可以调用从字典中获得的结果来执行它应该执行的任何操作。

Eg 例如

switcher[option]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM