Python: elif or new if?

后端 未结 5 712
谎友^
谎友^ 2021-01-04 21:52

What is better to use:

if var in X:
    #do_whatever
elif (var in Y):
    #do_whatever2

or:

if var in X:
    #do_whatever
i         


        
相关标签:
5条回答
  • 2021-01-04 22:25

    If you need to perform both checks, you should use two separate ifs. If you want to check one or the order you should always use elif because

    • It's more efficient. You will save resources if your first condition is true.
    • You can have unexpected errors if both conditions are true.

    Performance wise, you should also consider testing the most likely condition first.

    0 讨论(0)
  • 2021-01-04 22:34

    Looking at the code without knowledge of the data then the elif case explicitely states your intentions and is to be preferred.

    The two if statements case would also be harder to maintain as even if comments are added, they would still need to be checked.

    0 讨论(0)
  • 2021-01-04 22:37

    If var can't be in both X and Y, then you should use elif. This way, if var in X is true, you don't need to pointlessly eval var in Y.

    0 讨论(0)
  • 2021-01-04 22:42

    If the second statement is impossible if the first one is true (as is the case here, since you said var can't be in both X and Y), then you should be using an elif. Otherwise, the second check will still run, which is a waste of system resources if you know it's going to false.

    0 讨论(0)
  • 2021-01-04 22:51

    It makes a difference in some cases. See this example:

    def foo(var):
        if var == 5:
            var = 6
        elif var == 6:
            var = 8
        else:
            var = 10
    
        return var
    
    def bar(var):
        if var == 5:
            var = 6
        if var == 6:
            var = 8
        if var not in (5, 6):
            var = 10
    
        return var
    
    print foo(5)        # 6
    print bar(5)        # 10
    
    0 讨论(0)
提交回复
热议问题