[Tutor] calculator

Ignacio Vazquez-Abrams ignacio@openservices.net
Tue, 28 Aug 2001 13:43:36 -0400 (EDT)


Something else you can do, in conjunction with all the other really good
suggestions you've received so far, is to code your main menu (and in fact all
of your menus) similar to this:

---
def circlearea():
   ...

def squarearea():
   ...

def rectanglearea():
   ...

def squareroot():
   ...

def addnumbers():
   ...

menuoptions={'1':circlearea, '2':squarearea, '3':rectanglearea,
'4':squareroot, '5':addnumbers}

while 1:
  while 1:
    print "please choose an option"
    print
    print "1. circle area"
    print "2. square area"
    print "3. rectangle area"
    print "4. square root"
    print "5. add numbers"
    shape = input("> ")
    if not menuoptions.has_key(shape)
      print
      print "whoops thats not good"
      print
    else:
      break
  menuoptions[choice]()
---

That way finding the option is a matter of a lookup in a dictionary.

If you wanted to be REALLY clever you could do the following:

---
menuoptions={'1':(circlearea, 'circle area'), '2':(squarearea, 'square area'),
'3':(rectanglearea, 'rectangle area'), '4':(squareroot, 'square root',
'5':(addnumbers, 'add numbers')}

while 1:
  while 1:
    print "please choose an option"
    print
    for i in menuoptions.keys():
      print "%s. %s" % (i, menuoptions[i][1])
    shape = input("> ")
    if not menuoptions.has_key(shape)
      print
      print "whoops thats not good"
      print
    else:
      break
  menuoptions[choice][0]()
---

That way you get not only the valid inputs and the functions to call from the
dictionary, but also the descriptions to print in the menu. And adding new
functions is simply a matter of adding entries to the dictionary.

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