0

I am typing a python menu and i was wondering if there was a way to make the program return to a certain place. For instance:

print 'choose: '
a = raw_input (' apple[a], grape[g], quit[q] ')
if a=='a':
    print 'apple'
elif a=='g':
    print 'grape'
elif a=='q':
    print 'quit'
    print 'Are you sure?'
    print 'yes[y], no[n]'
    b=raw_input ('Choose: ')
    if b=='y':
        quit()
    elif b=='n':
      print 'returning to menu'

In the part where it is:

`b=raw_input ('Choose: ')
    if b=='y':
        quit()
    elif b=='n':
        print 'returning to menu'`

How would I return to the first apple\grape menu? Is there a way to do that so the user doesn't have to quit and instead return to the main menu?

Biswajit_86
  • 3,661
  • 2
  • 22
  • 36
Evantf
  • 45
  • 1
  • 1
  • 9

3 Answers3

2

One way to do that (adding to your own code):

while True:
    print 'choose: '
    a = raw_input (' apple[a], grape[g], quit[q] ')
    if a=='a':
        print 'apple'
    elif a=='g':
        print 'grape'
    elif a=='q':
        print 'quit'
        print 'Are you sure?'
        print 'yes[y], no[n]'
        b=raw_input ('Choose: ')
        if b=='y':
            quit()
        elif b=='n':
            print 'returning to menu'
            continue
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
1

Here is a version of your program which encloses the input/output in a while loop. I also use a dictionary to handle the options (a and g). It also does some error checking.When possible, use dictionaries to handle options; they are a lot cleaner than a multitude of if/else statements.

fruit = {'a': 'apple', 'g': 'grape'}
while True:
    option = raw_input("a, g, q: ")
    if len(option) != 1:
        break
    else:
        if option in fruit:  
            print fruit[option]
        elif option == 'q':
            quit = raw_input("Quit? ")
            if len(quit)!=1 or quit=='y':
                break
blasko
  • 690
  • 4
  • 8
1

I would either use a function recursively or a while loop. Since there are already while loop solutions, the recursive solution would be:

from sys import exit

def menu():
    a = raw_input("choose: apple[a], grape[g], quit[q] ")
    if a == 'a':
        return 'apple'
    elif a == 'g':
        return 'grape'
    elif a == 'q':
        print 'Are you sure you want to quit?'
        b = raw_input ('Choose: yes[y], no[n] ')
        if b == 'y':
            exit()
        elif b == 'n':
            return menu()  # This calls the function again, so we're asked question "a" again

menu() 
Dor-Ron
  • 1,787
  • 3
  • 15
  • 27