Bảng công văn, hoặc từ điển.
Bạn bản đồ phím aka. các giá trị của lựa chọn trình đơn cho các chức năng thực hiện các lựa chọn đã cho biết:
def AddRecordHandler():
print("added")
def DeleteRecordHandler():
print("deleted")
def CreateDatabaseHandler():
print("done")
def FlushToDiskHandler():
print("i feel flushed")
def SearchHandler():
print("not found")
def CleanupAndQuit():
print("byez")
menuchoices = {'a':AddRecordHandler, 'd':DeleteRecordHandler, 'c':CreateDatabaseHandler, 'f':FlushToDiskHandler, 's':SearchHandler, 'q':CleanupAndQuit}
ret = menuchoices[input()]()
if ret is None:
print("Something went wrong! Call the police!")
menuchoices['q']()
Hãy nhớ xác thực thông tin nhập của bạn! :)
Nguồn
2010-10-20 14:08:40
Sao chép tất cả những điều sau: http://stackoverflow.com/search?q=%5Bpython%5D+switch. –
Xem thêm câu hỏi [trường hợp chuyển đổi trong python không hoạt động; cần một mẫu khác] (http://stackoverflow.com/questions/3886641/switch-case-in-python-doesnt-work-need-another-pattern/3893242#3893242). – martineau