Python reduces the use of if else branch structure-using modular programming instead of if else branch structure

if elseThe branch structure is very useful, but the consequence of misusing it is to make the indentation level of the code very complicated.

def func(choice):
    if choice == 1:
        pass
    elif choice == 2:
        pass
    elif choice == 3:
        pass
    elif choice == 4:
        pass
    elif choice == 5:
        pass

This classic way of writing looks neat and beautiful, but it's actually not recommended. The reasons are as follows:
1. **Low efficiency. **If we choose the last option, it will still judge each item in front.
2. If the omitted code in the pass is more complicated, the indentation level will be more complicated.
The above can be improved by using the idea of ​​modular programming.
We first encapsulate the pass statement in the above code into functions, and become like this:

def func(choice):
    if choice == 1:
        func1()
    elif choice == 2:
        func2()
    elif choice == 3:
        func3()
    elif choice == 4:
        func4()
    elif choice == 5:
        func5()

Next consider how to remove the if elsestatement.
**Everything in python is an object. **You can use lists or tuples to store functions. Because tuples take up less memory than lists, it is recommended to use tuples.

def func(choice):
    func_list = (func1, func2, func3, func4, func5)
    func_list[choice]()

Guess you like

Origin blog.csdn.net/qq_46620129/article/details/112796351