Does it matter to use `if ... else` or` if ... return; {implicit else} `?

These two templates give the same results. Does it matter which one is used? Why?

I prefer the second one, it has less padding and just looks cleaner to me, but I haven't seen it used much (in the places I've been). I do not want to rely on anything and use it everywhere if for some reason it was advised.

IF ... ELSE

if not packages:
    help('download')
else:        
    for p in packages:
        do_download(p)
        verify_md5(p)
        etc(p)

      

IF ... RETURN; IMPLICIT ELSE

if not packages:
    help('download')
    return

for p in packages:            
    do_download(p)
    verify_md5(p)
    etc(p)

      

+3


source to share


2 answers


From Zen of Python :

Flat is better than nested.



So the second approach is more Pythonic.

I personally find flat code easier to read than nested code and less error-prone (for example, a statement else

that hasn't been lined up correctly can be difficult to debug). Of course, these are subjective judgments.

+6


source


It's a style thing ... But I always prefer to use else

. As you clearly state in the title of the question without having else

, it makes it implicit and I strongly believe in explicit code that is easy to read and understand.

Also from Zen of Python



Explicit is better than implicit.

      

+6


source







All Articles