if statements with or w/o else statements
Mark McEahern
mark at mceahern.com
Mon Feb 23 09:03:40 EST 2004
On Mon, 2004-02-23 at 07:31, Bart Nessux wrote:
> Should an if statement have a corresponding else statement?
Syntactically, the answer is no--the else statement is optional.
Logically, though, consider this:
if preCondition:
doSomething()
That is, e.g., you're testing for a pre-condition that, if false,
indicates failure. In that case, NOT having an else statement is likely
to mask subtle bugs and it's probably better to have:
if preCondition:
doSomething()
else:
raise RuntimeError('X must be true.')
which itself can be expressed differently so that you don't need the
else, e.g.,
if not preCondition:
raise RuntimeError(...)
doSomething()
;-)
Cheers,
// m
More information about the Python-list
mailing list