[Tutor] calculator

Ignacio Vazquez-Abrams ignacio@openservices.net
Wed, 29 Aug 2001 07:07:25 -0400 (EDT)


On Wed, 29 Aug 2001 alan.gauld@bt.com wrote:

> > suggestions you've received so far, is to code your main menu
> > (and in fact all of your menus) similar to this:
>
> And I'll add some more menu maintenance code...
>
> > menuoptions={'1':circlearea, '2':squarearea, '3':rectanglearea,
> > '4':squareroot, '5':addnumbers}
>
> def getMenuItem():
>     shape = 0
>     while shape not in '12345':   # validate the choice

Mmm. No, I don't like. Use 'not menuoptions.has_key(shape)' instead. Using in
will allow silly things like '12' and '234' through.

While you're at it, initialize shape with None instead. It just looks more
professional ;)

>       print "please choose an option"
>       print
>       print "1. circle area"     # or use loop/dictionary trick here
>       print "2. square area"
>       print "3. rectangle area"
>       print "4. square root"
>       print "5. add numbers"
>       shape = raw_input("> ")     # safer than input()
>     return shape
>
> choice = getMenuItem()
> menuoptions[choice]()
>
> If you combine that with the trick of printing out the
> menu choices from the dictionary and pass the dictionary
> into the getMenuItem function then you have a reusable
> menu function...
>
> However ISTR that Python already provides stuff for doing
> all of this in the cmd module... :-)

Bah! There's nothing wrong with first principles ;)

> Alan g.

-- 
Ignacio Vazquez-Abrams  <ignacio@openservices.net>