我正在尝试制作一个简单的字典映射,但是却收到一条错误消息,指出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)
答案 0 :(得分:3)
switcher
的定义将执行sys.exit()
,您的程序将结束。
您对switcher
的使用不是switch语句;它是一个字典,在其中您将键0
映射到sys.exit()
的返回值。为了确定该值并创建字典,执行sys.exit()
。 sys.exit()
退出程序。
最简单的解决方法是单独处理退出:
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")
或者您可以编写switcher
以便每个值都可调用:
switcher = {
1: add_student,
2: delete_student,
3: list_students,
4: search_students,
0: sys.exit,
}
并将值定义为函数,然后您可以调用从字典中获得的结果以执行应做的事情。
例如
switcher[option]()