新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)Python教程:python如何使用字典實現switch
1、構建字典。前面key的數字代表用戶輸入的功能序號。value代表相應的功能函數。

創(chuàng)新互聯(lián)主營亳州網站建設的網絡公司,主營網站建設方案,app軟件定制開發(fā),亳州h5成都微信小程序搭建,亳州網站營銷推廣歡迎亳州等地區(qū)企業(yè)咨詢
這些函數是根據業(yè)務需求實現的普通函數。
2、使用循環(huán)。捕捉用戶輸入,然后執(zhí)行。
實例
# -*- coding: UTF-8 -*-
"""
@author:AmoXiang
@file:28.使用字典實現 switch 結構.py
@time:2021/02/01
"""
def get_monday(): # 定義函數
return "星期一" # 返回星期一
def get_tuesday():
return "星期二" # 返回星期二
def get_wednesday():
return "星期三" # 返回星期三
def get_thursday():
return "星期四" # 返回星期四
def get_friday():
return "星期五" # 返回星期五
def get_saturday():
return "星期六" # 返回星期六
def get_sunday():
return "星期日" # 返回星期日
def get_default():
return "不知道星期幾" # 模擬swtich語句中的default語句功能
switcher = { # 通過字典映射來實現switch/case功能
1: get_monday, # 通過鍵不同,調用不同的函數
2: get_tuesday,
3: get_wednesday,
4: get_thursday,
5: get_friday,
6: get_saturday,
7: get_sunday
}
for i in range(2): # 測試2次
day = input("今天是一周第幾天?:").strip() # 手動輸入一個天數
if day.isdigit(): # 判斷是否是數字
day = int(day) # 轉換為int型
else:
day = 0 # 設置day值為0
day_name = switcher.get(day, get_default)() # 當day不在字典映射中時,調用get_default()
print(f"今天{day_name}")
以上就是python使用字典實現switch的方法,希望對大家有所幫助。更多Python學習指路:創(chuàng)新互聯(lián)Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
新聞標題:創(chuàng)新互聯(lián)Python教程:python如何使用字典實現switch
文章源于:http://m.5511xx.com/article/cosodsg.html


咨詢
建站咨詢
