[Tutor] dictionary swittching

alan.gauld@bt.com alan.gauld@bt.com
Thu, 16 May 2002 17:48:14 +0100


> From: Erik Price [mailto:erikprice@mac.com]

> > if (condition1)
> >     execute green code
> >     if (condition2)
> >         execute orange code
> > else
> >     execute red code
> >
> > It doesn't do what you (as a python programmer) would expect.  That

> Python doesn't have this problem, as long as you are coding in 
...
> the languages 
> I've played with since I started programming, none use 
> whitespace/indentation in this way, so I would HOPE that the 
> programmer takes a careful look at their braces usage and 
> continues to indent properly 

Unfortunately the dangling else problem s very common for C/Java 
etc programmers and we've nearly all been bitten at least once.
This is one of Pythons strongest points.

THe most common case is when you want the indentation shown, but 
in C etc you need to add a dummy else to achieve it:

> > if (condition1)
> >     execute green code
> >     if (condition2)
> >         execute orange code
        else {}   // needed to avoid the dangling else
> > else
> >     execute red code

The alternative (which I tend to use!) is to always use braces 
everytime, everywhere.

> > if (condition1){
> >     execute green code
> >     if (condition2){
> >         execute orange code
	  }
    }   // avoids the dangling else
> > else{
> >     execute red code
    }

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld