Cara menggunakan python switch case w3schools

Switch Case Python adalah fitur pemrograman yang kuat yang memungkinkan Anda mengontrol aliran program Anda berdasarkan nilai variabel atau ekspresi. Anda dapat menggunakannya untuk mengeksekusi blok kode yang berbeda, tergantung pada nilai variabel selama runtime.

Pada artikel kali ini, Codekey akan membahas tentang Switch Case Python serta cara penerapannya. Jika Anda tertarik dengan pembahasan tentang python switch case, simak terus artikel ini sampai akhir.

Python Switch Case : Definisi dan Syntax

Dalam pemrograman komputer, pernyataan switch case adalah sejenis sistem kontrol pemilihan yang digunakan untuk memungkinkan nilai variabel mengubah aliran kontrol eksekusi program.

Switch case statement mirip dengan pernyataan ‘if’ dalam bahasa pemrograman apa pun. Switch case statement adalah pengganti pernyataan ‘if..else’ dalam program apa pun. Keuntungan menggunakan Pernyataan Switch Case dalam program adalah sebagai berikut:

  • Lebih mudah untuk men-debug.
  • Lebih mudah untuk membaca program oleh siapa saja kecuali programmer.
  • Lebih mudah dipahami dan juga lebih mudah dipelihara.
  • Lebih mudah untuk memverifikasi semua nilai yang akan diperiksa ditangani.

Switch case Python biasanya ditemukan bahwa penggunaan pernyataan switch sangat jarang saat memprogram dalam bahasa python. Jadi, selalu muncul pertanyaan apakah bahasa python mendukung pernyataan switch case atau tidak? Nah, jawaban untuk pertanyaan ini adalah tidak.

Tidak seperti bahasa pemrograman lainnya, bahasa python tidak memiliki fungsi pernyataan switch. Ini juga merupakan pertanyaan jebakan bagi siswa untuk mendapatkan tugas python mereka. Jadi, kami menggunakan alternatif lain yang dapat menggantikan fungsionalitas pernyataan switch case dan membuat pemrograman lebih mudah dan lebih cepat.

Artikel Terkait  Tutorial Python 39 : Mengenal Python Extensions

Pengganti Switch Case Python

Untuk memudahkan pemrograman, Anda bisa menggunakan cara ini untuk menggantikan Switch Case dalam Bahasa Python. Lihatlah kode di bawah ini:

Artikel Terkait  Tutorial Python 10 : Fungsi pada Python, Bagaimana Cara Menggunakannya?

#include<bits/stdc++.h>
using namespace std;

// Function to convert number into string
string numbers_to_strings(int argument){
    switch(argument) {
        case 0:
            return "zero";
        case 1:
            return "one";
        case 2:
            return "two";
        default:
            return "nothing";
    };
};

// Driver program
int main()
{
    int argument = 0;
    cout << numbers_to_strings(argument);
    return 0;
}

Kode ini beranalog dengan kode yang diberikan dalam C++ :

#include<bits/stdc++.h>
using namespace std;

// Function to convert number into string
string numbers_to_strings(int argument){
    switch(argument) {
        case 0:
            return "zero";
        case 1:
            return "one";
        case 2:
            return "two";
        default:
            return "nothing";
    };
};

// Driver program
int main()
{
    int argument = 0;
    cout << numbers_to_strings(argument);
    return 0;
}

Output: 
Zero

Itulah penjelasan tentang cara menerapkan pengganti atau alternatif dari Python Switch Case. Jika Anda tertarik untuk belajar lebih banyak tentang Python, kunjungi dan simak seri tutorial Python di https://codekey.id/.

Most programming languages have a switch or case statement that lets you execute different blocks of code based on a variable. But does Python has a Switch statement? Now, Yes.

In this article, we will discuss Switch Case in Python, a new feature called match case with an example, how to use it, and 3 others methods for implementing it with code. So, let’s get started!

What is a Switch statement?

In computer programming, a switch case statement is a kind of selection control system used to allow the value of the variable to change the control flow of program execution. The switch case statement is similar to the ‘if’ statement in any programming language.

The switch case statement is a replacement of the ‘if..else’ statement in any program when we know that the choices are going to be integer or character literals. The advantages of using the Switch Case Statement in the program are as given below:

  1. It is easier to debug.
  2. It is easier to read the program to anyone except the programmer.
  3. It is easier to understand and also easier to maintain.
  4. It is easier to verify all values that are to be checked are handled.
  5. It makes the code concise.

Need of Switch Case Statement

While programming, there are times when we need to execute a specific block of code depending on some other situation. If the given situation does not satisfy, the code block is skipped and does not get executed.

If we check and apply these blocks of code manually without any format, the length and complexity of the code will increase. 

A switch statement is a useful tool for testing a variable against a number of possible values and executing different instructions based on the result. It is typically an improvement to add a switch statement to a program.

Switch Statement in C++/Java

Before moving towards learning the alternatives of switch case in python language and different ways to implement it let us first understand the switch case statement in C++ or Java language.

In the switch case statement, the variable is compared to the list of values. This value is known as a case value and the compiler keeps on checking the given value with all the cases until a match occurs.

The syntax for switch case statement in C++ is as given below:

switch(expression) {
   case constant-expression  :
      statement(s);
      break; //optional
   case constant-expression  :
      statement(s);
      break; //optional
  
   // multiple number of case statement is allowed 
   default : //Optional
      statement(s);
}

 

Explanation of code: 

  • Expression: It should be an integral type or enumerated type.
  • Constant expression: The constant expression should have the same data type as the variable to be compared with and also it must be literal or constant.
  • Break: The break statement is used to terminate the switch statement if the case value matches the variable value. After the break statement, the flow control of the program jumps to the next line of code immediately after the switch case statement.
  • Default: The default case is used in a switch statement for the situation where no case is executed. Declaring the default case is optional.                                                                                                   

Does Python have a Switch statement?

Yes, Python does have a Switch case functionality. Since Python 3.10, we can now use a new syntax to implement this type of functionality with a match case. The match case statement allows users to implement code snippets exactly to switch cases.

It can be used to pass the variable to compare and the case statements can be used to define the commands to execute when one case matches.

How to use match case in Python?

The match-case statement consists of a series of case blocks, each of which specifies a pattern to match against the value. If a match is found, the corresponding code block is executed. If no match is found, an optional default block can be used to specify a default action.

Python added this feature with the 3.10 release in October of 2021 under "Structural Pattern Matching". It can be implemented in a very similar manner as we do in C, Java, or Javascript. The match case command is more easier and powerful.

It consists of 2 main components :

  1. The “match” keyword
  2. The case clause(s) with each condition/statement

A pattern that matches the variable, a condition that determines whether the pattern matches, and a series of statements that are to be executed if the pattern matches make up the case clause.

For numerous potential results of a given variable, we can create numerous case statements. A pattern must be matched in each case statement.

Let's look at how to implement it:

Syntax:

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

 

Example:

user_input = int(input("enter your lucky number between 1-5\n"))

match user_input:

        case 1:

         print( "you will have a new house")

        case 2:

         print( "you will receive good news ")

        case 3:

         print( "you will get a car")

        case 4:

         print( "you might face your fear this week")

        case 5:

         print( "you will get a pet")

 

Output:

enter your lucky number between 1-5
5
you will get a pet

 

Other Alternatives

We can also use 3 different replacements to implement a python switch case:

  1. If-elif-else
  2. Dictionary Mapping
  3. Using classes

Let us understand each python switch syntax one by one in detail below:

Method 01) If-elif-else

If-elif is the shortcut for the if-else if-else chain. We can use the if-elif statement and add the else statement at the end which is performed if none of the above if-elif statements is true. The if-elif chain allows you to handle multiple conditions inside one block.

Example:

# if-elif statement example 

fruit = 'Banana'

if fruit == 'Mango': 
    print("letter is Mango") 

elif fruit == "Grapes": 
    print("letter is Grapes") 

elif fruit == "Banana": 
    print("fruit is Banana") 

else: 
    print("fruit isn't Banana, Mango or Grapes") 

 

Output:

fruit is Banana

 

Method 02) Dictionary Mapping

If you know the basic python language then you must be familiar with a dictionary and its pattern of storing a group of objects in memory using key-value pairs. So, when we use the dictionary to replace the Switch case statement, the key value of the dictionary data type works as cases in a switch statement.

Example:

# Implement Python Switch Case Statement using Dictionary

def monday():
    return "monday"
def tuesday():
    return "tuesday"
def wednesday():
    return "wednesday"
def thursday():
    return "thursday"
def friday():
    return "friday"
def saturday():
    return "saturday"
def sunday():
    return "sunday"
def default():
    return "Incorrect day"

switcher = {
    1: monday,
    2: tuesday,
    3: wednesday,
    4: thursday,
    5: friday,
    6: saturday,
    7: sunday
    }

def switch(dayOfWeek):
    return switcher.get(dayOfWeek, default)()

print(switch(3))
print(switch(5))

 

Output:

wednesday
friday

 

Method 03) Using classes

Along with the above methods to implement the switch case in python language, we can also use python classes to implement the switch case statement. An object constructor that has properties and methods is called a class.

So, let us see the example of performing a switch case using class by creating a switch method inside the python switch class.

Example:

class PythonSwitch:
    def day(self, dayOfWeek):

        default = "Incorrect day"

        return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()

    def case_1(self):
        return "monday"

 

    def case_2(self):
        return "tuesday"

 

    def case_3(self):
        return "wednesday"

   

    def case_4(self):
       return "thursday"

 

    def case_5(self):
        return "friday"

 

    def case_7(self):
        return "saturday"
    
    def case_6(self):
        return "sunday"

   
my_switch = PythonSwitch()

print (my_switch.day(1))

print (my_switch.day(3))

 

Output:

monday
wednesday

 

If you need more help, you can get in touch with our expert python tutors.

Conclusion

In this blog, we studied how to implement a Switch Case in Python programming. Now you also code for the python switch case to try it yourself. It is highly recommended to use it because it increases the coding efficiency and is easier to implement.

Apa itu Switch Case Javascript?

Belajar Javascript Part 10 : Switch Case Di JavascriptSwitch Case adalah fungsi yang berguna untuk membuat pengecekan sebuah nilai. dan nilai yang tersedia untuk pengecekan bisa banyak atau lebih dari satu.

Apa kegunaan statement switch case?

2. Switch Case Pernyataan switch adalah pernyataan pilihan ganda. Setelah Sahabat DQ memberikan pilihan dan ekspresi yang relevan untuk setiap pilihan, Itu melihat melalui pilihan sampai menemukan pilihan yang cocok dengan ekspresi dan mengeksekusinya.