Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Nested IF/ELSE and ELIF?

Is there any semantic or runtime difference between these two different code organizations? Or is it simply a matter of brevity and whitespace?

if something:
    ...
else:
    if other:
        ...
    else:
        ...

Vs.

if something:
    ...
elif other:
    ...
else:
    ...
like image 405
Austin Cory Bart Avatar asked Dec 18 '22 06:12

Austin Cory Bart


1 Answers

There is no logical difference. Prefer the second way, using elif, it's more readable.

Note that at the abstract syntax level, they are exactly equivalent:

>>> s1 = """\
... if something:
...     ...
... else:
...     if other:
...         ...
...     else:
...         ..."""
...         
>>> s2 = """\
... if something:
...     ...
... elif other:
...     ...
... else:
...     ..."""
...     
>>> ast.dump(ast.parse(s1)) == ast.dump(ast.parse(s2))
True

Specifically, the elif form is transformed into the nested if form of flow control:

>>> ast.dump(ast.parse(s2))
"Module(body=[If(test=Name(id='something', ctx=Load()), body=[Expr(value=Ellipsis())], orelse=[If(test=Name(id='other', ctx=Load()), body=[Expr(value=Ellipsis())], orelse=[Expr(value=Ellipsis())])])])"
>>> # pip install astdump
>>> astdump.indented(s2)
Module
  If
    Name
      Load
    Expr
      Ellipsis
    If
      Name
        Load
      Expr
        Ellipsis
      Expr
        Ellipsis
like image 57
wim Avatar answered Dec 21 '22 11:12

wim