转到 python 行?

Go to line in python?

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

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'`

我如何 return 到第一个 apple\grape 菜单?有没有办法让用户不必退出,而是 return 到主菜单?

这是您的程序的一个版本,它在一个 while 循环中包含了 input/output。我还使用字典来处理选项(a 和 g)。它还可能会出现一些错误checking.When,使用字典来处理选项;它们比大量 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 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

我要么递归地使用函数,要么使用 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()