Hướng dẫn switch case trong python

Cafedev chia sẻ cho ace cách tạo một swicth case đơn giản trong python cực đơn giản…

Sự thay thế của Switch Case trong Python là gì?

Không giống như mọi ngôn ngữ lập trình khác mà chúng ta đã sử dụng trước đây, Python không có câu lệnh switch hoặc câu lệnh case. Để giải quyết vấn đề này, chúng ta sử dụng dictionary mapping.

# -----------------------------------------------------------
#Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
#@author cafedevn
#Contact: 
#Fanpage: //www.facebook.com/cafedevn
#Group: //www.facebook.com/groups/cafedev.vn/
#Instagram: //instagram.com/cafedevn
#Twitter: //twitter.com/CafedeVn
#Linkedin: //www.linkedin.com/in/cafe-dev-407054199/
#Pinterest: //www.pinterest.com/cafedevvn/
#YouTube: //www.youtube.com/channel/UCE7zpY_SlHGEgo67pHxqIoA/
# -----------------------------------------------------------

# Function to convert number into string 
# Switcher is dictionary data type here 
def numbers_to_strings[argument]: 
    switcher = { 
        0: "zero", 
        1: "one", 
        2: "two", 
    } 
  
    # get[] method of dictionary data type returns  
    # value of passed argument if it is present  
    # in dictionary otherwise second argument will 
    # be assigned as default value of passed argument 
    return switcher.get[argument, "nothing"] 
  
# Driver program 
if __name__ == "__main__": 
    argument=0
    print numbers_to_strings[argument] 

Đoạn code này tương tự như đoạn code đã cho trong C ++:


#include 
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 >> week[2]
'Tuesday'
>>> week[0]
'Sunday'
>>> week[7]
'Invalid day of week'
>>> week[4.5]
'Invalid day of week'

a. Sử dụng Python Functions & Lambdas

Chúng ta cũng có thể sử dụng function và lambdas trong dict.

>>> def zero[]:
        return 'zero'
>>> def one[]:
        return 'one'
>>> def indirect[i]:
        switcher={
                0:zero,
                1:one,
                2:lambda:'two'
                }
           func=switcher.get[i,lambda :Invalid]
           return func[]
>>> indirect[4]Invalid>>> indirect[2]
'two'
>>> indirect[1]
'one'
>>> indirect[0.5]
'Invalid'

b. Thông qua Classes

Sử dụng class chó phép chúng ta chọn method ở thời điểm runtime.

>>> class Switcher[object]:
          def indirect[self,i]:
                   method_name='number_'+str[i]
                   method=getattr[self,method_name,lambda :'Invalid']
                   return method[]
def number_0[self]:
          return 'zero'
def number_1[self]:
          return 'one'
def number_2[self]:
          return 'two'
>>> s=Switcher[]
>>> s.indirect[2]
'two'
>>> s.indirect[4]
'Invalid'
>>> s.number_1[]
'one'

Tham khảo.

//data-flair.training/blogs/python-switch-case/

All rights reserved

Bài Viết Liên Quan

Toplist mới

Bài mới nhất

Chủ Đề