if statements with or w/o else statements

Harry George harry.g.george at boeing.com
Mon Feb 23 08:07:36 EST 2004


"Diez B. Roggisch" <nospam-deets at web.de> writes:

> Bart Nessux wrote:
> 
> > Should an if statement have a corresponding else statement? Or, is it OK
> > to have an if statement by itself. For completeness, it seems the two
> > should be together, but from experience I know that a if statement by
> > itself works just fine. Below is an example:
> 
> Only if you actually have s/t senseful to do in the else. Otherwise you end
> up with s/t like this:
> 
> if <cond>:
>   ...
> else:
>   pass
> 
> -- 
> Regards,
> 
> Diez B. Roggisch

The question is, why do you need a branch?   There are several reasons:

1. Exhaustive enumeration of valid paths, with an exception if none is
   detected.  

   The "enumeration" might be just one item:
   if x:
       do_x
   else:
       raise Ex01

   It might be a few:
   if x:
       do_x
   elif y:
       do_y
   else:
       raise Ex02

   It might be a whole lot of choices, in which case some table lookup
   should be used with the exception raised if no lookup case is
   found.
   

2. Partial Enumeration.  For this, we do not know that an exception
   has occurred if we fall off the list.  So we leave off the "else".
   Or for clarity, to make very clear that it is optional, we can use
   
   else:
       pass

   However, I only do that if there confusion on whether or not it
   really ought to be full enumeration.

-- 
harry.g.george at boeing.com
6-6M21 BCA CompArch Design Engineering
Phone: (425) 342-0007



More information about the Python-list mailing list