转到python中的第行?

转到python中的第行?,python,menu,return,Python,Menu,Return,我正在键入一个python菜单,我想知道是否有办法使程序返回到某个地方。例如: 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]'

我正在键入一个python菜单,我想知道是否有办法使程序返回到某个地方。例如:

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'
在其所在部分:

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

如何返回第一个apple\grape菜单?有没有办法让用户不必退出而返回主菜单?

这是一个将输入/输出包含在while循环中的程序版本。我还使用字典来处理选项(a和g)。它还进行一些错误检查。如果可能,使用字典来处理选项;它们比大量的if/else语句干净得多

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

这是一个将输入/输出封装在while循环中的程序版本。我还使用字典来处理选项(a和g)。它还进行一些错误检查。如果可能,使用字典来处理选项;它们比大量的if/else语句干净得多

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
一种方法(添加到您自己的代码中):

一种方法(添加到您自己的代码中):


我要么递归地使用函数,要么使用while循环。 由于已有while循环解决方案,递归解决方案将是:

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() 

我要么递归地使用函数,要么使用while循环。 由于已有while循环解决方案,递归解决方案将是:

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() 

使用
while True
循环,当用户输入
n
可能的重复项时,该循环将在程序上循环,以便在生成器上读取,并
产生
使用
while True
循环,当用户输入
n
可能的重复项时,它会在您的程序上循环,可能需要在生成器上读取,并且
产生