[Tutor] [Tutor]Text menus: How to implement

Alistair Campbell campbells4@ozemail.com.au
Tue, 13 Aug 2002 21:48:57 +1000


Hi All,

I am practicing with python and I am trying to implement a main menu and a
sub menu in text without a GUI.

The problem I am having with the logic of the following code is that I can
close the sub-menu and get to the main menu but when I try to quit from the
main menu I am left in the sub-menu without the introductory text. I know
this because if I enter a sub-menu choice it is the sub-menu function(s)
that get initiated.

As I say, I know I have got the logic of the 'while 1:' statements wrong
somehow. If someone can point out how that would be great. Any pointers to a
pattern for implementing text based menu's would also be a good learning for
me.

<<Code Snippet>>

initialisation...
a class...
some other functions...

def main():
    MainMenu()

def SaveUseMenu():
    print
    print "Would you like to Save or Use this model?"
    print
    print "Would you like to Save or Use this model?"
    print
    print "1. Save.\n"
    print "2. Save and Use. \n"
    print "3. Use.\n"
    print "4. Quit.\n"

    while 1:
        choice = float(raw_input("Enter your choice-->"))
        if choice == 1:
            SaveTheModel()
        if choice ==2:
            SaveAndUse()
        if choice == 3:
            Use()
        if choice == 4:
            break
        MainMenu()

def MainMenu():
    print
    print "A General Decision Analysis Program."
    print
    print "Have You Ever Had to Make Up Your Mind?"
    print
    print "Enter the number for your choice.\n"
    print "1. Open existing model.\n"
    print "2. Create a new model.\n"
    print  "3. Quit.\n"
    print

    while 1:

        choice = float(raw_input("Enter your choice-->"))

        if choice == 1:
            OpenModel()
        if choice == 2:
            NewModel()
        if choice == 3:
            print "Quitting the Decisioner.\n"
            print "Bye for now"
            break

if __name__ == '__main__':
    main()

<<End code snippet>>

All the best.

Alistair Campbell