when to use if vs elif in python

后端 未结 6 1527
醉话见心
醉话见心 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:19

    In some cases, elif is required for correct semantics. This is the case when the conditions are not mutually exclusive:

    if x == 0:   result = 0
    elif y == 0: result = None
    else:        result = x / y
    

    In some cases it is efficient because the interpreter doesn't need to check all conditions, which is the case in your example. If x is negative then why do you check the positive case? An elif in this case also makes code more readable as it clearly shows only a single branch will be executed.

提交回复
热议问题