Cara menggunakan switch python

Cara menggunakan switch python
Niguru.com | Minggu, 31 Jan 2021 | Pada bahasa pemrograman lain seperti VB (Visual Basic), Delphi, Javascript, mempunyai instruksi Case atau instruksi Switch yang digunakan untuk pengambilan keputusan dalam kondisi dimana opsi yang tersedia cukup banyak.

Pada Python instruksi Case dan Switch tidak tersedia. Sebagai gantinya Python menyediakan instruksi ELIF yang dapat digabungkan penggunaannya dengan instruksi atau fungsi IF, sehingga dapat digunakan untuk pengambilan keputusan dalam kondisi dimana opsi yang tersedia banyak.

Sintaks Elif adalah sebagai berikut:

elif kondisi: instruksi

Elif adalah instruksi pelengkap If maka perhatikan penggunaannya ditempatkan setelah If. Perhatikan pada contoh berikut ini:

a=input("ketik angka: ")

b=input("ketik angka: ")

print "----------------"

print "a =",a

print "b =",b

if b>a:print("b lebih besar dari a")

elif a>b:print("a lebih besar dari b") 

else:print("a sama dengan b")

print "----------------"

Cara menggunakan switch python

 

Simpan dengan nama ifelse02.py (boleh disimpan dengan nama lain):

Cara menggunakan switch python

 

Jalankan file ifelse02 pada DOS. Hasilnya:

Cara menggunakan switch python

 

Berikut ini contoh apabila Elif digunakan untuk menampilkan opsi yang lebih banyak:

a=input("ketik angka 1..4: ") 

print "a =",a

print "----------------"

if a==1:print "anda mengetik angka",a 

elif a==2:print "anda mengetik angka",a 

elif a==3:print "anda mengetik angka",a 

elif a==4:print "anda mengetik angka",a 

else:print "anda mengetik angka yang salah" 

print "----------------"

Cara menggunakan switch python

 

Simpan dengan nama ifelse03.py (boleh disimpan dengan nama lain):

Cara menggunakan switch python

 

Jalankan file ifelse03 pada DOS. Hasilnya:

Cara menggunakan switch python

Demikianlah penjelasan mengenai cara penggunaan instruksi Elif pada bahasa pemrograman Python.

Selamat mencoba .. Have a nice day :-)

www.Niguru.com (Nino Guevara Ruwano)

Learn about Python Switch Case.

Table of Contents

  • Introduction to Python Switch Case
  • What is Switch Case in Python?
  • How to implement Python Switch Case?
  • Python Switch Case using dictionary
  • Python Switch Case Using Functions
  • Python Switch Case Using Lambdas
  • Switch Case using Python Classes
  • Return Value
  • Python Switch Case using if-elif-else
  • Application of Switch Case in Python

Abstract

Python Switch Case is a selection control statement. The switch expression is evaluated once. The value of the expression is compared with the values of each case, if there is a match, the associated block of code is executed. Unlike other languages, Python doesn't have its inbuilt switch case statements so we have to implement it by using different methods. All of these methods are explained in the article. Read along to know more.

Introduction to Python Switch Case

Ever wondered how menu-driven program (A program that obtains input from a user by displaying a list of options) works. As these program takes input from the users, they just has to check the condition matching to the input. For this purpose, we have to use Python Switch Case statements. Read along to know more.

What is Switch Case in Python?

The if makes a decision based on whether the condition is true or not. If the condition is true, it evaluates the indented expression however, if the condition is false, the indented expression under else will be evaluated. When we need to run several conditions, you can place as many elif conditions as necessary between the if condition and the else condition. Switch case statements are a substitute for long if statements that compare a variable to several integral values

  • The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
  • Switch is a control statement that allows a value to change control of execution.

But unline different languages python doesn't have it's inbuilt switch case statements. Read along to know more, how we can use switch case statements in python.

This flow chart clearly shows the working of the switch case. This shows that first of all the conditions are checked one by one and after that if not a single statement gets true, then a default statement will get implemented.

How to implement Python Switch Case?

Unlike C++/Java, python doesn't have its inbuilt Switch Case statement. There are several alternative methods by which we can implement Switch Case statements in python. These methods are:

1. With help of dictionaries

  • By using functions

  • By using Lambdas

2. With help of classes

3. With help of if-elif-else statements

Let's see each of the methods to implement python switch case statement one by one with the help of examples. Read along ot know more.

Python Switch Case using dictionary

If you are familiar 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. Moreover, there are 2 different ways to implement Switch Case using Dictionary. These are:

  1. Using Functions
  2. Using Lambda Functions

Python Switch Case Using Functions

When we use the dictionary to replace the Switch case statement, the key of the dictionary data type works as cases in a switch statement. We just need to define some functions which are considered as values in dictionaries. When we call these value with help of keys then the particular function gets invoked and we got the desired output.

We are going to implement switch case in python by dictionaries with the help of functions.

Example

In this example, we are converting a number to its number name.

Code

def one():
    return "one"
def two():
    return "two"
def three():
    return "three"
def four():
    return "four"
def five():
    return "five"
def six():
    return "six"
def seven():
    return "seven"
def eight():
    return "eight"
def nine():
    return "nine"
def default():
    return "no spell exist"

numberSpell = {
    1: one,
    2: two,
    3: three,
    4: four,
    5: five,
    6: six,
    7: seven,
    8: eight,
    9: nine
    }

def spellFunction(number):
    return numberSpell.get(number, default)()

print(spellFunction(3))
print(spellFunction(10))

Output

Explanation

  • We create different functions which return the number names of the number.
  • Then, we create a dictionary in which we have stored different key-value pairs.
  • After creating dictionary, we created a main function which takes user input for finding the number name.
  • At the end, we have called the function to print the desired output.

Python Switch Case Using Lambdas

We are going to implement switch case in python by dictionaries with the help of lambda functions. Lambda functions are the small anonymous functions which can take n numbers of parameters but only have single expression.

When we use the dictionary to replace the Switch case statement, the key of the dictionary data type works as cases in a switch statement. We just need to define anonymous lambda functions which are considered as values in dictionaries. When we call these value with help of keys then the particular function gets invoked and we got the desired output.

Let's understand basics of lambda functions.

Syntax of Lambda Function

lambda parameters: expression

We have to use a lambda keyword for creation of lambda function, then we have to pass parameters and expression to it with : seperating them.

Code

a = lambda number: number*10

print(a(2))

Output

Explanation

  • We have created a lambda function which accepts one parameter and returns a single expression, which return the number by multiplying it by 10.
  • Then we print the variable by passing a number to it.
  • At the end, we got the desired output.

Let's move to the example to understand how we can use dictionaries with help of lambda functions for implementing switch-case statements in python.

Example

In this example, we are converting a number to its number name.

Code

def one():
    return "one"
def two():
    return "two"
def three():
    return "three"

def spellFunction(number):
    numberSpell = {
        1: one,
        2: two,
        3: three,
        4: lambda: "four"
    }

    return numberSpell.get(number, lambda: "no number spell exist")()

print(spellFunction(1))
print(spellFunction(7))

Output

one
no number spell exist

Explanation

  • We create different functions which returns the number names of the number.
  • Then, we have created a main function in which we create a dictionary in which we have stored different key-value pairs.
  • Inside the dictionary we have used the lambda function.
  • This main function returns the number name of the number, if it is available in dictionary. If not avaiable then it will return the default value.
  • At the end, we have called the function to print the desired output.

Switch Case using Python Classes

We can use Python Classes to implement Switch Case in python. Class in python is termed as the combination of properties and method inside it. Let's see with the help of the example how we can implement switch case using classes.

We have to use getattr function which is used for implementing of switch case by using classes. Let's understand in brief about this function.

Syntax

getattr(object, name, default)

This is the syntax of getattr which is accepts 3 parameters object, name and default. All the 3 parameters are explained below. Read along to know more.

Parameters

Getattr accepts 3 parameter which is used for implementation of conditional statement(switch case) using classes. These parameters are:

  1. object(MANDATORY PARAMETER): object name whose attribute is to be returned.
  2. name(MANDATORY PARAMETER): string that contains the attribute name of the object.
  3. default(OPTIONAL PARAMETER): if the attribute is not present in object then default statement is returned.

Return Value

This function returns the name of the attributes which is present in object, which finally gives us the output. If the attribute is not present we will get a default value.

Example

We are going to create an example in which we are checking whether the entered digit is binary or not. If it is binary_0 then our function will return zero as an output on the other hand if it is binary_1 then our function will return one as an output but if the digit entered is other than 0 & 1 then our code will return not a binary digit. Let's code this example for better understanding.

Code

class binaryOrNot():
    def mainFunction(self,i):
            method_name='binary_'+str(i)
            method = getattr(self,method_name,lambda: 'not a binary digit')
            return method()
    def binary_0(self):
            return 'zero'
    def binary_1(self):
            return 'one'
binary=binaryOrNot()
print(binary.mainFunction(1))

Output

Explanation

  • Firstly, we have created a class which will return us whether the number inputed is binary or not.
  • Then, we create various functions inside the class to check wheter a number is binary or not.
  • We have used a method getattr() which is basically used to check the conditions.
  • After that we called the class and used it's function to implement the switch case in python.

Python Switch Case using if-elif-else

The if…elif…else statement is used in Python for decision making and it can be replaced with switch case in python with all the switch conditions in if & elif sections and the default condition in the else section.

The if makes a decision based on whether the condition is true or not. If the condition is true, it evaluates the indented expression however, if the condition is false, the indented expression under else will be evaluated. When we need to run several conditions, you can place as many elif conditions as necessary between the if condition and the else condition.

Syntax

if(condition):
    statement
elif(condition):
    statement
else:
    statement

This is the if-elif-else chain where we have to pass the condition into the if & elif and else is the default statement which gets executed if no conitions above it are false.

Example

Suppose you have a number stored into the variable and you have to check whether a number is negative, in between 1-10, or greater that 10. Let's code this problem.

Code

number = 15

if(number < 0):
    print('number is a negative number')
elif(1 <= number <= 10):
    print('number lies in between of 1 and 10')
else:
    print('number is greater than 10')

Output

number is greater than 10

Explanation

  • Firstly, we assigned a number to a variable.
  • Then, we use give conditional statements to the if and elif blocks
  • After assigning the conditions to if-elif we return the statement from these blocks/.
  • At the end we use else statement which is used when if no other conditions above it are not satisfied.

Application of Switch Case in Python

As we saw, in the introduction section that MENU DRIVEN PROGRAMS requires switch case to get implemented. We will write code here to create a menu driven program with the help method if-elif-else statements. Let's code it for better understanding.

Code

print('Welcome to Scaler Academy')
print('1. visit python hub')
print('2. visit dsa hub')
print('3. visit java hub')
print('4. more')

print('input the suitable option in the next line:')
textInput = int(input())

if(textInput == 1):
    print('Thank you. We are redirecting to python hub.')

elif(textInput == 2):
    print('Thank you. We are redirecting to dsa hub.')

elif(textInput == 3):
    print('Thank you. We are redirecting to java hub.')

elif(textInput == 4):
    print('Thank you. We are redirecting to more section.')
else:
    print('wrong input')

Output

Welcome to Scaler Academy
1. visit python hub
2. visit dsa hub
3. visit java hub
4. more


input the suitable option in the next line:
2
Thank you. We are redirecting to dsa hub.

Conclusion

  • First of all, we understand what is Switch Case in python.
  • Then we get to know that, python doesn't have it's inbuilt switch case statements.
  • After that, we learn 3 different ways for implementation of switch case in python.
  • Last but not least we have implemented a practical application with the help of switch case.

Apa itu Switch Case python?

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.

Apa fungsi dari switch case?

2. Switch Case Saat Sahabat DQ memeriksa nilai tertentu, switch case function akan memeriksa ekspresi mana yang dimiliki oleh nilai tersebut dan kemudian menjalankan blok kasus itu.

Apa penggunaan Python?

Python adalah sebuah bahasa pemrograman yang digunakan untuk membuat aplikasi, perintah komputer, dan melakukan analisis data. Sebagai general-purpose language, Python bisa digunakan untuk membuat program apa saja dan menyelesaikan berbagai permasalahan. Selain itu, Python juga dinilai mudah untuk dipelajari.

Kata kunci manakah yang digunakan untuk membuat fungsi di python?

Fungsi dalam Python didefinisikan menggunakan kata kunci def. Setelah def ada nama pengenal fungsi diikut dengan parameter yang diapit oleh tanda kurung dan diakhir dingan tanda titik dua :. Baris berikutnya berupa blok fungsi yang akan dijalankan jika fungsi dipanggil.