[Tutor] Suggestions for cleaner code

Matt Richardson marichar@csusb.edu
Tue Jul 8 20:19:01 2003


On Tue, 2003-07-08 at 16:59, Kalle Svensson wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> [Matt Richardson]
> > Hi all,
> 
> > I'm starting to get the hang of this, but am looking for some
> > criticism to keep me on track.  One of the exercises in 'Core
> > Python' is to create a program that asks a user to select an
> > operation to run, run the program, then prompt for another operation
> > until an escape command is given.  After screwing around with it for
> > a couple of days, here's what I've got:
> 
> Basically, it's looking good.  Since you asked, I've tried to find a
> pair of suggestions for improvement, though.
> 
> > loop = 0
> > while (loop == 0):
> >     option = input('Option: ')
> ...
> >     else:
> >         print 'Farewell'
> >         loop = 1
> 
> This is more commonly written as:
> 
>   while True:
>       option = input()
>   ...
>       else:
>           print 'Farewell'
>           break
> 
> Eliminates the variable "loop", but otherwise works the same.

Yes.  I didn't like the 'loop' variable, but kept thinking in terms of
BASIC (20 years ago) and a GOTO line that would repeat the 'input' line.
> 
> Now for the interesting part, the if statement:
> 
> >     if (1 <= option <= 3):
> >         if option == 1:
> >             print 'Hello'
> >         elif option == 2:
> >             print 'I should have paid more attention in math classes.'
> >         elif option == 3:
> >             print 'Why did I sleep through class?'
> 
> A good way to make this easier to extend (e.g. with new menu choises)
> is to use a dictionary.  Consider:
> 
>   options = {1: ('Greeting', 'Hello'),
>              2: ('Discussion', 'I should have paid more attention '
>                                'in math classes.'),
>              3: ('Question', 'Why did I sleep through class?')
>              'default': ('Farewell', 'Farewell')}
> 
> Can you figure out a way to replace the beginning prints and the if
> statements with something simpler (that won't have to be modified for
> adding new menu choises) using this data structure?
> 
The dictionary approach is far more elegant than the one I took.  Thanks
for the pointers.

Matt