when to use if vs elif in python

后端 未结 6 1529
醉话见心
醉话见心 2020-12-13 04:20

If I have a function with multiple conditional statements where every branch gets executed returns from the function. Should I use multiple if statements, or if/elif/else? F

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 05:16

    In general (e.g. your example), you would always use an if..elif ladder to explicitly show the conditions are mutually-exclusive. It prevents ambiguity, bugs etc.

    The only reason I can think of that you might ever not use elif and use if instead would be if the actions from the body of the preceding if statement (or previous elif statements) might have changed the condition so as to potentially make it no longer mutually exclusive. So it's no longer really a ladder, just separate concatenated if(..elif..else) blocks. (Leave an empty line between the separate blocks, for good style, and to prevent someone accidentally thinking it should have been elif and 'fixing' it)

    Here's a contrived example, just to prove the point:

    if total_cost>=10:
        if give_shopper_a_random_discount():
            print 'You have won a discount'
            total_cost -= discount
        candidate_prime = True
    
    if total_cost<10:
        print 'Spend more than $10 to enter our draw for a random discount'
    

    You can see it's possible to hit both conditions, if the first if-block applies the discount, so then we also execute the second, which prints a message which would be confusing since our original total had been >=10.

    An elif here would prevent that scenario. But there could be other scenarios where we want the second block to run, even for that scenario.

    if total_cost<10:
        
    

提交回复
热议问题