2015-07-11 10 views
0

我輸入一個python菜單,我想知道是否有辦法讓程序返回到某個地方。例如:轉到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'` 

我將如何回到第一個蘋果\葡萄菜單?有沒有辦法做到這一點,使用戶不必退出,而是返回到主菜單?

+0

使用'而TRUE'循環,當用戶輸入'它會遍歷您的程序[N' –

+0

可能重複是否有標籤/轉到Python?](http://stackoverflow.com/questions/438844/is-there-a-label-goto-in-python) – NightShadeQueen

+0

可能想閱讀發電機和'yield' – boardrider

回答

2

我要麼使用遞歸函數或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() 
1

這裏是一個版本的程序,其包圍在一個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 
2

的一種方式做到這一點(添加到您自己的代碼):

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