Python實踐44-如何實現switch-case

Python裡面沒有switch-case

  • Python社區認為使用if-elif-else結構完全能夠做到和switch-case一樣的事情
  • 曾經有一些關於switch-case表達式的提案,因為支持的人不多,所以沒有能被採納

如何實現類似功能

  • 使用if-elif-else結構,適用於選擇分支不多的情況,例如:

if __name__ == __main__:
option = raw_input("input:")
if option == "start":
print("start app")
elif option == "stop":
print("stop app")
elif option == "restart":
print("restart app")

  • 使用字典+函數,適用於選擇分支多的情況。字典的key是條件,值是滿足條件時執行的目標函數,例如:

def start_app():
print("start app")

def stop_app():
print("stop app")

def restart_app():
print("restart app")

switch = {
"start": start_app,
"stop": stop_app,
"restart": restart_app
}

if __name__ == __main__:
option = raw_input("input:")
switch[option]()

代碼下載

本系列文章和代碼已經作為項目歸檔到github,倉庫地址:jumper2014/PyCodeComplete。大家覺得有幫助就請在github上star一下,你的支持是我更新的動力。什麼?你沒有github賬號?學習Python怎麼可以沒有github賬號呢,快去註冊一個啦!


推薦閱讀:

TAG:Python | Python入門 | Python開發 |