Como usar funções Switch-Case em Python

As funções switch-case não são nativas do Python, mas você pode implementá-las usando dicionários ou classes. Aprenda como usar funções switch-case em Python com exemplos.

O que é uma instrução Switch em Python?

Em geral, o switch é um mecanismo de controle que testa o valor armazenado em uma variável e executa as instruções case correspondentes. A instrução Switch Case introduz o fluxo de controle em seu programa e garante que seu código não fique sobrecarregado por múltiplas instruções ‘if’.

Conseqüentemente, seu código parece meticuloso e transparente para os visualizadores. É um recurso de programação maravilhoso que os programadores usam para implementar o fluxo de controle em seu código. A instrução Switch Case funciona comparando os valores especificados nas instruções case com variáveis ​​em seu código.
 

Uma instrução switch case do Python permite que um computador selecione uma das várias rotas de execução possíveis, dependendo do valor de uma expressão especificada, o que ajuda a agilizar os procedimentos de tomada de decisão. Agora, surge a pergunta ‘o Python tem instrução switch case?’. Devemos saber que switch-case não é suportado nativamente pelo Python; no entanto, podemos obter resultados comparáveis ​​com métodos alternativos.

Método 1: Expressões If-Elif

A Base: Estrutura Básica para if-elif

A maneira mais comum de simular switch case em Python é usar instruções if-elif. Mais de 15,7 milhões de desenvolvedores usam Python como sua principal linguagem de codificação. Usando uma expressão de entrada como guia, este método fundamental gera uma sequência de condições if-elif representando muitos cenários.

Um método alternativo de gerenciar diversas condições, que difere da estrutura if-elif tradicional, é demonstrado no exemplo da instrução switch do Python, conforme ilustrado abaixo:

switch_case_example(input_value) def:
    If ‘case1’ is the value of input_value:
        #Code in case #1
    If input_value is equal to ‘case2’:
        #Code in case #2
    If input_value == ‘case3’, then
        # Case 3 code
    #… more elif criteria as necessary
    alternatively:
        # Default scenario when none of the parameters are met

Você pode usar esta estrutura para executar blocos de código específicos de acordo com o valor de input_value. Mesmo que este método funcione, pode tornar-se oneroso à medida que o número de casos aumenta.

Simplificação de código: maximizando cadeias if-elif

As cadeias if-elif podem se tornar complicadas à medida que o número de casos aumenta, afetando a legibilidade e a manutenção do código. Investigamos métodos para otimizar e organizar essas cadeias para resolver isso.

Usar o recurso alternativo da instrução if-elif é um método. Permite que um caso passe para o próximo caso sua condição não seja atendida. Quando muitos casos devem executar o mesmo código, este exemplo de instrução de caso Python ajuda:

O código def otimizado_switch_case(input_value) deve ser copiado.

    If input_value is present in (‘case1’, ‘case2’, ‘case3’), then
        # Programming for cases 1, 2, and 3. elif input_value == ‘case4’:
        # Programming for case number four: elif input_value == ‘case5’
        # Case 5 code #… more elif conditions as required else:
        # Default scenario when none of the parameters are met

Este método encurta o código e elimina redundância.

Elegant Python: empregando dicionários para troca de caso em Python

Os dicionários em Python fornecem uma maneira sofisticada e eficiente de criar lógica switch-case. Você pode criar um dicionário onde os valores correspondam aos blocos de código relacionados e as chaves representem casos no lugar de uma sequência de expressões if-elif, conforme ilustrado abaixo.

Switch case using dictionary def input_value(input_value):
    cases: ~
        ‘case1’: print(“Code for case1”), lambda
        ‘case2’: print(“Code for case2”), lambda
        ‘case3’: print(“Code for case3”), lambda
        #… additional instances as required
    # If input_value is not in cases, default case
    cases.get(lambda: print(“Default case”), input_value)Then

Este método segue os princípios de design claros e expressivos do Python, ao mesmo tempo que agiliza e simplifica seu código.

Agora que você sabe a resposta para “existe switch case em Python?” e “O Python oferece suporte a switch case?”, você pode usar a sintaxe de switch do Python com habilidade tornando-se proficiente nessas estratégias de instrução if-elif. Você pode então modificar sua abordagem de acordo com a complexidade e os requisitos de escalabilidade do seu código.

Método 2: Empregando Casos em Funções

Aproveitando ao Máximo as Funções: Determinando Funções de Caso

Usar funções como casos é outra maneira de simular a sintaxe de switch case do Python. Este método confere a cada cenário uma função própria, melhorando a legibilidade e modularidade do código. Vamos ver como aplicar essa estratégia na prática.

Etapa 1: Definir as funções do caso

Fornece funções distintas que capturam o comportamento específico relacionado a cada cenário. Por exemplo:

case1() def:
    print(“Case 1: Executing Code”)
case2() def
    print(“Case 2: Executing Code”)
case3() def:
    print(“Case 3 is being executed”)
#… provide more case functions as necessary

A organização e a facilidade de manutenção do código são aprimoradas pelo fato de que cada função contém a lógica relevante para um cenário específico.

Etapa 2: construir um dicionário de mapeamento

Crie agora um dicionário que associe nomes de casos às suas funções correspondentes:

Replicate the code case_functions = { ‘case1’: case1, ‘case2’: case2, ‘case3’: case3, #… other cases as required }

Este dicionário vincula nomes de casos às suas funções correspondentes como uma tabela de consulta.

Execução em Movimento: Execução em Movimento de um Caso

Você pode executar funções de caso dinamicamente com base na entrada do usuário se tiver funções que representem casos e um dicionário que mapeie nomes de casos para funções em vigor. Sua mudança em Python ganha flexibilidade com sua execução dinâmica.

Etapa 3: Conduzir funções de caso dinâmico 

Crie um sistema que receba informações do usuário, procure a função apropriada no dicionário e depois a execute. Aqui está um exemplo:

Replique este código: function execute_case(case_name):

    # Use the dictionary to get the matching function: case_function = case_functions.get(case_name)
    In the event that case_function: case_function(), #execute the case function
    alternatively:
        output(“Case not found”)
Using user_input as an example, input(“Enter a case:”)
run the case (user input)

Ao integrar-se perfeitamente com a entrada do usuário, este sistema permite a execução de determinadas funções de caso em resposta ao nome do caso inserido.

Usar essa abordagem resulta em uma estrutura de código expansível e modular. Portanto, basta declarar ou alterar funções para adicionar ou modificar situações, melhorando a capacidade de manutenção e escalabilidade de sua aplicação. A instrução case em Python enfatiza ser limpa e modular para estar alinhada com o uso de funções como casos.

Método 3: listando comportamento semelhante ao switch

A classe Enum em Python: gerando enumerações

Com a ajuda da classe Enum do Python, podemos criar facilmente enumerações e incluir uma troca de caso em Python com programas estruturados. As enumerações fornecem um método claro e estruturado para expressar diferentes situações dentro de um programa. Eles são simplesmente uma coleção de valores nomeados.

Etapa 1: estabeleça uma lista

Vamos começar revisando os fundamentos de fazer enumerações com um caso selecionado em Python. Você pode definir uma enumeração como esta usando o módulo enum:

from a list import. List
MyEnum(Enum) class:
    Case No. 1
    Case No. 2
    Case No. 3
    #… add more instances as necessary

Aqui, CASE1, CASE2 e CASE3 representam os três casos separados que compõem a enumeração MyEnum. Um valor distinto é atribuído a cada opção de caso em Python, dando ao seu código uma representação concisa e compreensível das diversas situações em que ele pode se deparar.

Usando a Força: Switch-Case com Listagens

Agora que temos nossa enumeração, vamos investigar como usá-la para imitar um caso selecionado em expressões switch-case do Python.

 Etapa 2: usando enumerações em instruções do tipo switch

As enumerações fornecem uma solução mais Pythonic para estruturas convencionais de switch-case. A seguir está uma ilustração de como usar enumerações em uma instrução case em Python:

Alterne entre maiúsculas e minúsculas usando enum (case) def:

    # When using Python 3.10 and later, a match statement
    case of match:
        MyEnum.CASE1 case:
            print(“CASE1’s executing code”)
        a MyEnum case.Case #2
            print(“CASE2’s executing code”)
        MyEnum.CASE3 case:
            print(“CASE3 is being executed”)
        issue _:
            “Default case” is printed.
# Usage example:
Using enum, switch case (MyEnum.CASE2)

Neste exemplo de switch do Python, projetamos uma estrutura semelhante a switch-case usando uma instrução match (introduzida pela primeira vez em Python 3.10). Como cada caso é definido explicitamente, o código é mais fácil de compreender e mantém a expressividade pela qual o Python é conhecido.

As vantagens da listagem

Existem vários benefícios em usar enumerações em Python para comportamento semelhante ao switch-case.

  • Legibilidade: usar enumerações para expressar vários cenários é um método claro e autodocumentado.
  • Manutenção: O código permanece ordenado e adicionar ou alterar casos é simples.
  • Pythonic: Este método segue a simplicidade e a clareza da sintaxe de switch do Python.

O uso de enumerações melhora a legibilidade e a beleza do seu código Python e oferece uma solução alternativa confiável para situações que exigem lógica switch-case. Essa abordagem é especialmente eficaz se seu aplicativo lidar com um número limitado de cenários exclusivos.

Método 4: aplicando decoradores a ações semelhantes a switch

Em Python, os decoradores podem ser ferramentas muito úteis. Vamos entender o uso de decoradores para construir um mecanismo switch-case para melhorar a capacidade de manutenção e organização do código.

Criando Decoradores de Caso em Design

Descubra o mundo do design de decoradores de caixas. Aprenda como criar e usar decoradores, funções especializadas que oferecem uma lógica switch-case lógica e estruturada para melhor manutenção e legibilidade de scripts Python.

Selecionando Casos Dinamicamente com Decoradores

Um sistema versátil que pode ser adaptado a diversas condições é obtido combinando decoradores e seleção dinâmica de caixas. Essa combinação torna as modificações adaptáveis ​​e melhora a capacidade de resposta do sistema. Exemplos ilustrativos demonstrarão como usar essas técnicas na programação Python do mundo real.

Como implementar a instrução Python Switch Case

Se você sempre codificou em linguagens como C++ ou Java, pode achar estranho que Python não tenha uma instrução switch case. Em vez disso, o Python oferece inúmeras soluções alternativas, como um dicionário, classes Python ou funções lambda do Python para implementar instruções switch-case. 

Se você quiser saber o motivo exato por trás de não ter uma instrução switch case em python, verifique PEP 3103

Antes de nos aprofundarmos nessas alternativas, vamos primeiro ver como uma função switch case normalmente funciona em outras linguagens de programação.

No exemplo abaixo, usamos a linguagem de programação C

switch (monthOfYear) {

    case 1:

        printf(“%s”, January);

        break;

    case 2:

        printf(“%s”, February);

        break;

    case 3:

        printf(“%s”, March);

        break;

    case 4:

        printf(“%s”, April);

        break;

    case 5:

        printf(“%s”, May);

        break;

    case 6:

        printf(“%s”, June);

        break;

    case 7:

        printf(“%s”, July);

        break;

   case 8:

        printf(“%s”, August);

        break;

    case 9:

        printf(“%s”, September);

        break;

    case 10:

        printf(“%s”, October);

        break;

    case 11:

        printf(“%s”, November);

        break;

    case 12:

        printf(“%s”, December);

        break;

    default:

        printf(“Incorrect month”);

        break;

    }

Agora, vamos aprofundar caso switch Python alternativas de função e entender como essas alternativas funcionam com a ajuda de exemplos.

Usando mapeamento de dicionário

Se você está familiarizado com outras linguagens de programação, então deve saber que o dicionário usa pares chave-valor para armazenar um grupo de objetos na memória. Quando você usa um dicionário como alternativa às instruções switch-case, as chaves do par chave-valor funcionam como um caso. 

O exemplo a seguir mostra a implementação da instrução switch case usando um dicionário. Aqui, estamos definindo uma função mês() para imprimir qual mês é o mês do ano.

Primeiro, comece criando instruções de caso e escreva funções individuais para cada caso. Certifique-se de escrever uma função que resolva o caso padrão.

def january():

    return “January”

def february():

    return “February”

def march():

    return “march”

def april():

    return “April”

def may():

    return “may”

def june():

    return “June”

def july():

    return “July”

def august():

    return “august”

def september():

    return “September”

def october():

    return “October”

def november():

    return “November” 

def december():

    return “December”

def default():

    return “Incorrect month”

A seguir, crie um objeto de dicionário em Python e armazene todas as funções que você definiu em seu programa.

switcher = {

    0: ‘january’,

    1: ‘february’,

    2: ‘march’,

    3: ‘april’,

    4: ‘may’,

    5: ‘june’,

    6: ‘july’,

    7: ‘august’,

    8: ‘september’,

    9: ‘october’,

    10: ‘november’,

    11: ‘december’

    }

Por último, crie uma função switch em seu programa que deve aceitar um número inteiro como entrada, realizar uma pesquisa no dicionário e invocar as funções correspondentes.

def month(monthOfYear):

    return switcher.get(monthOfYear, default)()

O código completo ficará assim

def january():

    return “January”

def february():

    return “February”

def march():

    return “march”

def april():

    return “April”

def may():

    return “may”

def june():

    return “June”

def july():

    return “July”

def august():

    return “august”

def september():

    return “September”

def october():

    return “October”

def november():

    return “November” 

def december():

    return “December”

def default():

    return “Incorrect month”

    

switcher = {

    0: ‘january’,

    1: ‘february’,

    2: ‘march’,

    3: ‘april’,

    4: ‘may’,

    5: ‘june’,

    6: ‘july’,

    7: ‘august’,

    8: ‘september’,

    9: ‘october’,

    10: ‘november’,

    11: ‘december’

    }

def month(monthOfYear):

    return switcher.get(monthOfYear, default)()

print(switch(1))

print(switch(0))

O código acima imprime a seguinte saída

February

January

Usando classes Python

Você também pode usar classes Python como alternativa à implementação de instruções switch-case. Uma classe é um construtor de objeto que possui propriedades e métodos. Vamos entender isso melhor com a ajuda do mesmo exemplo acima. Aqui, definiremos um método switch dentro de uma classe switch Python.

Exemplo

Primeiro, definiremos um método switch dentro de uma classe switch do Python que usa um mês do ano como argumento e converte o resultado em uma string.  

class PythonSwitch:

    def month(self, monthOf Year):

        default = “Incorrect month”

        return getattr(self, ‘case_’ + str(monthOf Year), lambda: default)()

Nota: No exemplo acima, usamos duas coisas: palavra-chave lambda e método getattr(). 

  • Usamos a palavra-chave lambda para definir uma função anônima em Python. A palavra-chave Lambda invoca a função padrão quando um usuário insere uma entrada inválida.
  • O método getattr() é usado para invocar uma função em Python.

Agora, crie funções individuais para cada caso.

def january(self):

        return “January”

 

    def february(self):

        return “February”

   def march(self):

        return “March”

   

   def april(self):

        return “April”

 

    def may(self):

        return “May”

 

    def june(self):

        return “June”

   def july(self):

        return “July”

 

    def august(self):

        return “August”

 

    def september(self):

        return “September”

   def october(self):

        return “October”

 

    def november(self):

        return “November”

 

    def december(self):

        return “December”

O código completo ficará assim

Switch-case functions are not native to Python, but you can implement them using dictionaries or classes. Learn how to use switch-case functions in Python with examples.

What is a Switch Statement in Python?
In general, the switch is a control mechanism that tests the value stored in a variable and executes the corresponding case statements. Switch case statement introduces control flow in your program and ensures that your code is not cluttered by multiple ‘if’ statements.

Hence, your code looks meticulous and transparent to viewers. It is a wonderful programming feature that programmers use to implement the control flow in their code. Switch case statement works by comparing the values specified in the case statements with variables in your code.
 

A Python switch case statement enables a computer to select one of several possible execution routes depending on the value of a specified expression, which helps to streamline decision-making procedures. Now, the question arises ‘does Python have switch case statement?’. We should know that switch-case is not supported natively by Python; nonetheless we can get comparable results with alternative methods.

Method 1: If-Elif Expressions
The Basis: Basic Structure for if-elif
The most common way to simulate switch case in Python is to use if-elif statements. More than 15.7 million developers use Python as their main coding language. Using an input expression as a guide, this fundamental method generates a sequence of if-elif conditions representing many scenarios.

An alternative method of managing several conditions, which differs from the traditional if-elif structure, is demonstrated in the Python switch statement example as illustrated below:

switch_case_example(input_value) def:
    If ‘case1’ is the value of input_value:
        #Code in case #1
    If input_value is equal to ‘case2’:
        #Code in case #2
    If input_value == ‘case3’, then
        # Case 3 code
    #… more elif criteria as necessary
    alternatively:
        # Default scenario when none of the parameters are met
You can use this structure to run particular code blocks according to the value of input_value. Even while this method works, it may become burdensome when the number of cases increases.

Code Simplification: Maximizing if-elif Chains
If-elif chains may grow cumbersome as the number of cases rises, affecting the code’s readability and maintainability. We investigate methods to optimize and arrange these chains to address this.

Using the if-elif statement’s fall-through feature is one method. It enables a case to move on to the next if its condition is not met. When many cases should run the same code, this Python case statement example helps:

The code def optimized_switch_case(input_value) should be copied.

    If input_value is present in (‘case1’, ‘case2’, ‘case3’), then
        # Programming for cases 1, 2, and 3. elif input_value == ‘case4’:
        # Programming for case number four: elif input_value == ‘case5’
        # Case 5 code #… more elif conditions as required else:
        # Default scenario when none of the parameters are met
This method shortens the code and eliminates redundancy.

Elegant Python: Employing Dictionaries for Case Switch in Python
The dictionaries in Python provide a sophisticated and efficient way to create switch-case logic. You can make a dictionary where the values correspond to the related code blocks, and the keys represent cases in place of a sequence of if-elif expressions, as illustrated below.

Switch case using dictionary def input_value(input_value):
    cases: ~
        ‘case1’: print(“Code for case1”), lambda
        ‘case2’: print(“Code for case2”), lambda
        ‘case3’: print(“Code for case3”), lambda
        #… additional instances as required
    # If input_value is not in cases, default case
    cases.get(lambda: print(“Default case”), input_value)Then
This method adheres to Python’s clear and expressive design principles while also streamlining and simplifying your code.

Now that you know the answer to “is there switch case in Python?” and “Does Python support switch case?”, you can use Python switch syntax skillfully by becoming proficient in these if-elif statement strategies. You can then modify your approach according to your code’s complexity and scalability requirements.

Method 2: Employing Cases in Functions
Making the Most of Functions: Determining Case Functions
Using functions as cases is another way to simulate Python switch case syntax. This method gives each scenario its own function, improving the code’s readability and modularity. Let’s see how to apply this strategy in practice.

Step 1: Define the Case Functions

Provide distinct functions that capture the particular behavior related to each scenario. For instance:

case1() def:
    print(“Case 1: Executing Code”)
case2() def
    print(“Case 2: Executing Code”)
case3() def:
    print(“Case 3 is being executed”)
#… provide more case functions as necessary
The organization and maintainability of the code are enhanced by the fact that each function contains the logic relevant to a particular scenario.

Step 2: Construct a Mapping Dictionary

Create a dictionary now that associates case names with their corresponding functions:

Replicate the code case_functions = { ‘case1’: case1, ‘case2’: case2, ‘case3’: case3, #… other cases as required }
This dictionary links case names to their corresponding functions as a lookup table.

Execution in Motion: Execution in Motion of a Case
You can dynamically execute case functions based on user input if you have functions representing cases and a dictionary that maps case names to functions in place. Your switch in Python gains flexibility from its dynamic execution.

Step 3: Conduct Dynamic Case Functions 

Create a system that receives input from the user, looks up the appropriate function in the dictionary, and then runs it. Here’s one instance:

Replicate this code: function execute_case(case_name):

    # Use the dictionary to get the matching function: case_function = case_functions.get(case_name)
    In the event that case_function: case_function(), #execute the case function
    alternatively:
        output(“Case not found”)
Using user_input as an example, input(“Enter a case:”)
run the case (user input)
By seamlessly integrating with user input, this system enables the execution of certain case functions in response to the case name entered.

Using this approach results in an expandable and modular code structure. It, therefore, only takes declaring or changing functions to add or modify situations, improving the maintainability and scalability of your application. The case statement in Python emphasizes being clean and modular to be aligned with the use of functions as cases.

Method 3: Listing Switch-Like Behavior
The Enum Class in Python: Generating Enumerations
With the help of Python’s Enum class, we can easily create enumerations and include a case switch in Python with structure programs. Enumerations provide a neat and structured method of expressing different situations within a program. They are simply a collection of named values.

Step 1: Establish a List

Let’s begin by reviewing the fundamentals of making enumerations with a select case in Python. You may define an enumeration like this by using the enum module:

from a list import. List
MyEnum(Enum) class:
    Case No. 1
    Case No. 2
    Case No. 3
    #… add more instances as necessary
Here, CASE1, CASE2, and CASE3 represent the three separate cases comprising the enumeration MyEnum. A distinct value is assigned to each case switch in Python, giving your code a concise and comprehensible depiction of the various situations it may run into.

Using the Force: Switch-Case with Listings
Now that we have our enumeration, let’s investigate how to use it to mimic a select case in Python switch-case expressions.

 Step 2: Using Enumerations in Switch-Like Statements

Enumerations provide a more Pythonic solution to conventional switch-case structures. The following is an illustration of how to use enumerations within a case statement in Python:

Switch case using enum (case) def:

    # When using Python 3.10 and later, a match statement
    case of match:
        MyEnum.CASE1 case:
            print(“CASE1’s executing code”)
        a MyEnum case.Case #2
            print(“CASE2’s executing code”)
        MyEnum.CASE3 case:
            print(“CASE3 is being executed”)
        issue _:
            “Default case” is printed.
# Usage example:
Using enum, switch case (MyEnum.CASE2)
In this Python switch example, we design a switch-case-like structure using a match statement (first introduced in Python 3.10). Because every case is defined explicitly, the code is easier to comprehend and retains the expressiveness for which Python is renowned.

The Advantages of Listing
There are various benefits to using enumerations in Python for switch-case-like behavior.

Readability: Using enumerations to express various scenarios is a clear and self-documenting method.
Maintainability: The code stays orderly, and adding or changing cases is simple.
Pythonic: This method adheres to the simplicity and clarity of Python switch syntax.
Using enumerations improves the readability and beauty of your Python code and offers a reliable workaround for situations requiring switch-case logic. This approach is especially effective if your application deals with a limited number of unique scenarios.

Method 4: Applying Decorators to Switch-Like Action
In Python, decorators can be very useful tools. Let’s understand the use of decorators to construct a switch-case mechanism to improve the code’s maintainability and organization.

Creating Case Decorators in Design
Discover the world of designing case decorators. Learn how to create and use decorators, specialized functions that offer a logical and structured switch-case logic for better maintainability and readability of Python scripts.

Selecting Cases Dynamically with Decorators
A versatile system that may be tailored to various conditions is achieved by combining decorators and dynamic case selection. This combination makes modifications adaptable and improves system responsiveness. Illustrative examples will demonstrate how to use these techniques in real-world Python programming.

How to Implement Python Switch Case Statement
If you have always coded in languages like C++ or Java, you may find it odd that Python does not have a switch case statement. Instead, Python offers numerous workarounds like a dictionary, Python classes, or Python lambda functions to implement switch-case statements. 

If you want to know the exact reason behind not having a switch case statement in python, then you should check PEP 3103. 

Before diving deep into these alternatives, let us first see how a switch case function typically works in other programming languages.

In the below example, we have used the C programming language
switch (monthOfYear) {

    case 1:

        printf(“%s”, January);

        break;

    case 2:

        printf(“%s”, February);

        break;

    case 3:

        printf(“%s”, March);

        break;

    case 4:

        printf(“%s”, April);

        break;

    case 5:

        printf(“%s”, May);

        break;

    case 6:

        printf(“%s”, June);

        break;

    case 7:

        printf(“%s”, July);

        break;

   case 8:

        printf(“%s”, August);

        break;

    case 9:

        printf(“%s”, September);

        break;

    case 10:

        printf(“%s”, October);

        break;

    case 11:

        printf(“%s”, November);

        break;

    case 12:

        printf(“%s”, December);

        break;

    default:

        printf(“Incorrect month”);

        break;

    }

Now, let us go further into Python switch case function alternatives and understand how these alternatives work with the help of examples.

Using Dictionary Mapping
If you are familiar with other programming languages, then you must be knowing that the dictionary uses key-value pairs to store a group of objects in memory. When you are using a dictionary as an alternative to switch-case statements, keys of the key-value pair work as a case. 

The following example shows the implementation of the switch case statement using a dictionary. Here, we are defining a function month() to print which month, a month of the year is.

First, start by creating case statements and write individual functions for each case. Make sure that you write a function that tackles the default case.

def january():

    return “January”

def february():

    return “February”

def march():

    return “march”

def april():

    return “April”

def may():

    return “may”

def june():

    return “June”

def july():

    return “July”

def august():

    return “august”

def september():

    return “September”

def october():

    return “October”

def november():

    return “November” 

def december():

    return “December”

def default():

    return “Incorrect month”

Next, create a dictionary object in Python and store all the functions that you have defined in your program.

switcher = {

    0: ‘january’,

    1: ‘february’,

    2: ‘march’,

    3: ‘april’,

    4: ‘may’,

    5: ‘june’,

    6: ‘july’,

    7: ‘august’,

    8: ‘september’,

    9: ‘october’,

    10: ‘november’,

    11: ‘december’

    }

Lastly, create a switch function in your program that should accept integer as an input, performs a dictionary lookup, and invokes the corresponding functions.

def month(monthOfYear):

    return switcher.get(monthOfYear, default)()

The complete code will look like this
def january():

    return “January”

def february():

    return “February”

def march():

    return “march”

def april():

    return “April”

def may():

    return “may”

def june():

    return “June”

def july():

    return “July”

def august():

    return “august”

def september():

    return “September”

def october():

    return “October”

def november():

    return “November” 

def december():

    return “December”

def default():

    return “Incorrect month”

    

switcher = {

    0: ‘january’,

    1: ‘february’,

    2: ‘march’,

    3: ‘april’,

    4: ‘may’,

    5: ‘june’,

    6: ‘july’,

    7: ‘august’,

    8: ‘september’,

    9: ‘october’,

    10: ‘november’,

    11: ‘december’

    }

def month(monthOfYear):

    return switcher.get(monthOfYear, default)()

print(switch(1))

print(switch(0))

The above code prints the following output
February

January

Using Python Classes
You can also use Python classes as an alternative to implementing switch-case statements. A class is an object constructor that has properties and methods. Let us understand this further with the help of the same above example. Here, we will define a switch method inside a Python switch class.

Example
First, we will define a switch method inside a Python switch class that takes a month of the year as an argument, converts the result into a string.  

class PythonSwitch:

    def month(self, monthOf Year):

        default = “Incorrect month”

        return getattr(self, ‘case_’ + str(monthOf Year), lambda: default)()
Note: In the above example, we have used two things: keyword lambda and getattr() method. 

We use the lambda keyword to define an anonymous function in Python. Lambda keyword invokes the default function when a user enters invalid input.
getattr() method is used to invoke a function in Python.
Now, create individual functions for each case.

def january(self):

        return “January”

 

    def february(self):

        return “February”

   def march(self):

        return “March”

   

   def april(self):

        return “April”

 

    def may(self):

        return “May”

 

    def june(self):

        return “June”

   def july(self):

        return “July”

 

    def august(self):

        return “August”

 

    def september(self):

        return “September”

   def october(self):

        return “October”

 

    def november(self):

        return “November”

 

    def december(self):

        return “December”

The complete code will look like this
class PythonSwitch:

    def month(self, monthOf Year):

        default = “Incorrect month”

        return getattr(self, ‘case_’ + str(monthOf Year), lambda: default)()

    def january(self):

        return “January”

 

    def february(self):

        return “February”

 

    def march(self):

        return “March”

   

   def april(self):

        return “April”

 

    def may(self):

        return “May”

 

    def june(self):

        return “June”

   def july(self):

        return “July”

 

    def august(self):

        return “August”

 

    def september(self):

        return “September”

   def october(self):

        return “October”

 

    def november(self):

        return “November”

 

    def december(self):

        return “December”

my_switch = PythonSwitch()

print (my_switch.month(1))

print (my_switch.month(10))

O código acima imprime a seguinte saída

January

October

#python 

Como usar funções Switch-Case em Python
1.20 GEEK