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:
...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With