[Tutor] Return to main menu

Dragonfirebane at aol.com Dragonfirebane at aol.com
Tue Jun 29 02:07:05 EDT 2004


In a message dated 6/29/2004 1:48:01 AM Eastern Standard Time, 
game at gameweave.com writes:
Well this is the little program that I have created it is my first one and it 
works just
fine from what I have tested. Only problem I have with it is that, lets say 
you enter
1 at the prompt it will load the add.py modual. however when it comes to the 
end
of the modual it terminats. How would I go about making it so that it will 
return to 
the menu and ask for another choice.

Kevin

print """
0 Exit
1 Add
2 Subtract

"""
number = raw_input("Enter a number: ")

while 1:
        try:
            number = int(number)
            break
        except ValueError:
            print "That is not an option"
            number = raw_input("Enter a number: ")
if int(number) == 1:
        import add
if int(number) == 2:
        import subtract
just put the entire thing within a while loop and put a break or change the 
condition (from True to False) if they select exit, like so:

a = True
while a:
    print """
0 Exit
1 Add
2 Subtract

"""
    number = raw_input("Enter a number: ")

    while 1:
            try:
                number = int(number)
                break
            except ValueError:
                print "That is not an option"
                number = raw_input("Enter a number: ")
    if int(number) == 0:
            a = False
    if int(number) == 1:
            import add
    if int(number) == 2:
            import subtract

by the way: you can just as easily make the menu be part of the number prompt 
like so:

number = raw_input("""Enter a number:
1: Add
2: Subtract
3: Exit
...    """)

using the above code, you'd have to change the program so that it read:

a = True
while a:
    number = raw_input("""Enter a number:
1: Add
2: Subtract
3: Exit
...    """)

    while 1:
            try:
                number = int(number)
                break
            except ValueError:
                print "That is not an option"
                number = raw_input("Enter a number: ")
    if int(number) == 1:
            import add
    if int(number) == 2:
            import subtract
    if int(number) == 3: 
            a = False

HTH,
Orri

Email: dragonfirebane at aol.com
AIM: singingxduck
Programming Python for the fun of it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040629/cc84ece4/attachment-0001.html


More information about the Tutor mailing list