[Tutor] Newbie problems

Kirby Urner urnerk@qwest.net
Tue, 05 Mar 2002 10:00:05 -0800


>
>Second, I don't know if this was already been posted but
>I want to make a simple "text menu" in order to choose
>what functions/sub-programs shall be executed.  My problem
>is, how will I "ignore" the wrong type of choices?  Please
>consider my simple text menu below:
>
>- - - < s n i p > - - -
>
>- MY SIMPLE PROGRAM -
>
>[1] Sub-program 1
>[2] Sub-program 2
>[3] Sub-program 3
>[4] Sub-program 4
>[5] Sub-program 5
>[Q/q] Exit
>
>Please enter your choice:

Here's a simple menu template based on the above.

def mainmenu():
         switch = [f1,f2,f3,f4,f5]
         while 1:
           print """

- MY SIMPLE PROGRAM -

[1] Sub-program 1
[2] Sub-program 2
[3] Sub-program 3
[4] Sub-program 4
[5] Sub-program 5
[Q/q] Exit

"""
           userselect = raw_input("Your selection?: ")
           if userselect.upper()=="Q":
              break  #escape from loop
            else:
              try:
                  menuchoice = int(userselect)-1
              except:  # doesn't convert to integer
                  print "Please select 1-5 or Q/q
                  continue  # loop from top
          if not menuchoice>4 and not menuchoice<0:
                switch[menuchoice]()  # valid index, execute
          else:
               print "Please select 1-5 or Q/q" # out of range

If it doesn't work, please check indentation -- cut and
pasted from IDLE.

Note:  use of raw_input to get string, conversion to
integer but trapping error if it doesn't convert.

The "subprograms" (non-Python terminology) are all
top-level functions, and must already be defined for the
above to work.  I've used simple stub functions:

def f1(): print "Menu option 1"
def f2(): print "Menu option 2"
def f3(): print "Menu option 3"
def f4(): print "Menu option 4"
def f5(): print "Menu option 5"

Since Python doesn't have a switch statement, I've
initialized an array ('switch') and filled it with
pointers to (names of) these function objects.

A user selection which passes the convert-to-integer
and not-too-big-and-not-too-small tests gets to
serve as an index to this array.  But the user choice
was decremented by 1, as arrays are 0-indexed.

As these are callable function-objects, simply sticking
() after the selection (e.g. f1) causes execution thereof.

>Last but not the least, what is "gotoxy" of Pascal in Python?

Sorry, never heard of it.  Trying to position stuff on
screen?

Kirby

"You acknowledge that Software is not designed, licensed
or intended for use in the design, construction, operation
or maintenance of any nuclear facility." -- Java license
agreement