What is the difference between "else: return True" and "Return True?"

When I learn Python, I came across some different styles. I'm wondering what the difference is between using "else" as opposed to just putting the code outside of the "if" statement. To further explain my question, here are two blocks of code below.

x = 5
if x == 5:
    return True
else:
    return False

      

I understand that this returns False if x! = 5, but how does this code below differ from the code above? Is this the same or is there a slight difference? Is there an advantage to using one over the other?

x = 5
if x == 5:
    return True
return False

      

+3


source to share


2 answers


There is no difference in your code because the part if

ends with a symbol return

if the condition is true and the code will exit anyway. And if the condition is false, the branch else

also ending in will execute return

, so else

not required.

It's a matter of style, but one could argue that the second option is preferable, IMHO easier to read and with less drift to the right - in fact, some languages ​​/ compilers will flag it with a warning because it else

would be unnecessary.



The key point here is that when both branches have a conditional end with return

, then else

it is optional. But if it isn't, then you need to use else

, otherwise you end up executing code that was not intended. For example, here you cannot delete else

:

if n > 10:
  n = 1
else:
  n *= 10

      

+6


source


There is a very slight difference, but this is one you don't really care about. Considering these two features:

def f1():
    x = 5
    if x == 5:
        return True
    else:
        return False

def f2():
    x = 5
    if x == 5:
        return True
    return False

      

Look at the byte code resulting from each one:



>>> dis.dis(f1)
  4           0 LOAD_CONST               1 (5)
              2 STORE_FAST               0 (x)

  5           4 LOAD_FAST                0 (x)
              6 LOAD_CONST               1 (5)
              8 COMPARE_OP               2 (==)
             10 POP_JUMP_IF_FALSE       16

  6          12 LOAD_CONST               2 (True)
             14 RETURN_VALUE

  8     >>   16 LOAD_CONST               3 (False)
             18 RETURN_VALUE
             20 LOAD_CONST               0 (None)
             22 RETURN_VALUE
>>> dis.dis(f2)
 11           0 LOAD_CONST               1 (5)
              2 STORE_FAST               0 (x)

 12           4 LOAD_FAST                0 (x)
              6 LOAD_CONST               1 (5)
              8 COMPARE_OP               2 (==)
             10 POP_JUMP_IF_FALSE       16

 13          12 LOAD_CONST               2 (True)
             14 RETURN_VALUE

 14     >>   16 LOAD_CONST               3 (False)
             18 RETURN_VALUE

      

For the first function, Python still generates a couple of instructions for the unreachable implied return None

.

+5


source







All Articles