python no switch (to write several functions instead of switch)

One common use of dictionary instead of switch

In the C / C ++ / Java language, there is a very handy function switch, for example:

Copy the code code is as follows:

public class test {  
      
    public static void main(String[] args) {  
        String s = "C";  
        switch (s){  
        case "A":   
            System.out.println("A");  
            break;  
        case "B":  
            System.out.println("B");  
            break;  
        case "C":  
            System.out.println("C");  
            break;  
        default:  
            System.out.println("D");  
        }  
    }  
}  

 

In Python to achieve the same function,
method is to use if, else statement to achieve, such as:

from __future__ import division  
  
def add(x, y):  
    return x + y  
  
def sub(x, y):  
    return x - y  
  
def mul(x, y):  
    return x * y  
  
def div(x, y):  
    return x / y  
  
def operator(x, y, sep='+'):  
    if   sep == '+': print add(x, y)  
    elif sep == '-': print sub(x, y)  
    elif sep == '*': print mul(x, y)  
    elif sep == '/': print div(x, y)  
    else: print 'Something Wrong'  
  
print __name__  
   
if __name__ == '__main__':  
    x = int(raw_input("Enter the 1st number: "))  
    y = int(raw_input("Enter the 2nd number: "))  
    s = raw_input("Enter operation here(+ - * /): ")  
    operator(x, y, s)  

 

Method two, the ingenious use a dictionary to achieve the same function switch, such as:

Copy the code code is as follows:

#coding=gbk  
  
from __future__ import division  
  
x = int(raw_input("Enter the 1st number: "))  
y = int(raw_input("Enter the 2nd number: "))  
  
def operator(o):  
    dict_oper = {  
        '+': lambda x, y: x + y,  
        '-': lambda x, y: x - y,  
        '*': lambda x, y: x * y,  
        '/': lambda x, y: x / y}  
    return dict_oper.get(o)(x, y)  
   
if __name__ == '__main__':    
    o = raw_input("Enter operation here(+ - * /): ")  
    print operator(o)  

Guess you like

Origin www.cnblogs.com/wen-/p/12168757.html