Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Dictionary to implement switch in python

Shulou Source: shulou.com Published: 2022-06-03 17:35:49 09月29日 Update

This article mainly introduces python how to use a dictionary to achieve switch, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

1. Build a dictionary. The number of the previous key represents the function serial number entered by the user. Value represents the corresponding function.

These functions are common functions that are implemented according to business requirements.

2. Use cycle. Capture user input and execute.

Example

#-*-coding: UTF-8-*-"@ author:AmoXiang@file:28. Implement the switch structure .py @ time:2021/02/01 "def get_monday (): # define the function return" Monday "# return Monday def get_tuesday (): return" Tuesday "# return Tuesday def get_wednesday (): return" Wednesday "# return Wednesday def get_thursday (): return" Thursday "# Return Thursday def get_friday (): return "Friday" # return Friday def get_saturday (): return "Saturday" # return Saturday def get_sunday (): return "Sunday" # return Sunday def get_default (): return "I don't know what day of the week" # function of default statement in simulated swtich statement switcher = {# pass Dictionary mapping to implement switch/case function 1: get_monday # through different keys Call different functions 2: get_tuesday, 3: get_wednesday, 4: get_thursday, 5: get_friday, 6: get_saturday 7: get_sunday} for i in range (2): # Test twice day = input ("what day is today?:"). Strip () # manually enter a number of days if day.isdigit (): # determine whether it is a numeric day = int (day) # convert to int else: day = 0 # set the daytime value to 0 day_name = switcher.get (day) Get_default) () # when day is not in the dictionary map Call get_default () print (f "Today {day_name}") to thank you for reading this article carefully. I hope the article "how to use a dictionary to achieve switch in python" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Week dictionary function function article input different representative number user statement normal business value interest at the same time days instance serial number manual Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Huawei Linux macOS MySQL