when to use if vs elif in python

后端 未结 6 1535
醉话见心
醉话见心 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 04:52

    elif is a bit more efficient, and it's quite logical: with ifs the program has to evaluate each logical expression every time. In elifs though, it's not always so. However, in your example, this improvement would be very, very small, probably unnoticeable, as evaluating x > 0 is one of the cheapest operations.

    When working with elifs it's also a good idea to think about the best order. Consider this example:

    if (x-3)**3+(x+1)**2-6*x+4 > 0:
        #do something 1
    elif x < 0:
        #do something 2
    

    Here the program will have to evaluate the ugly expression every time! However, if we change the order:

    if x < 0:
       #do something 2
    elif (x-3)**3+(x+1)**2-6*x+4 > 0:
       #do something 1
    

    Now the program will first check if x < 0 (cheap and simple) and only if it isn't, will it evaluate the more complicated expression (btw, this code doesn't make much sense, it's just a random example)

    Also, what perreal said.

提交回复
热议问题