What is the difference between "else: return True" and just "return True?"
As I learn Python I have encountered some different styles. I am wondering what the difference between using "else" is as opposed to just putting 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 is returning False if x != 5, but how does this code below contrast to the code above? Is it the exact same thing, or is there a slight difference? Is there a benefit of using one over the other?
x = 5 if x == 5: return True return False
In your code, there isn't any difference, because the
ifpart ends with a
returnif the condition is true, and the code will exit anyway. And if the condition is false, the
elsebranch will be executed, also ending with a
return, so the
elseis not required.
It's a matter of style, but it can be argued that the second option is preferred, IMHO is simpler to read and with less rightward drift - in fact some languages/compilers will flag it with a warning, because the
elsewould be unnecessary.
The key point here is that when both branches of a conditional end with a
elseis not mandatory. But if that's not the case, then you need to use
else, otherwise you'll end up executing code that was not intended. For example, here you can not remove the
if n > 10: n = 1 else: n *= 10
There is a very slight difference, but it is one you wouldn't actually care about. Given these two functions:
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:
>>> 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 pair of instructions for the unreachable implied