2013-12-13 53 views
0

我想製作一個以選擇模式開始的程序。然後它應該保持該模式,直到我給它命令返回模式選擇。像這樣:回到代碼的開頭

input=raw_input('Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n') 

if input=='1': 
    while True: 
     #code 

if input=='2': 
    while True: 
     #code 

if input=='3': 
    while True: 
     #code 

哪個是最好的和最短的方式,使它回到模式選擇與某些命令?

感謝

+3

提示:您應該命名變量一樣的內置插件之一克制。這樣做會掩蓋它們,從而使它們在當前範圍內無法使用。 – iCodez

回答

3

使用break走出去的(內部)while True循環:

while True: 
    input=raw_input('Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n') 

    if input=='1' 
     while True: 
      #code 
      if something_happens: 
       break 

    elif input=='2': 
     while True: 
      #code 

    elif input=='3': 
     while True: 
      #code 

欲瞭解更多有關break,請參閱官方文檔here

1

如何將模式選擇放在自己的函數中,那麼你可以隨時調用該函數?

def get_mode(): 
    input=raw_input('Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n') 
    return input 
0

您應該像評論中提到的那樣避免使用內置變量名稱,如input

更多權利這樣做的方法是由字典選擇函數,並處理意外輸入的異常。所有嵌套在main中的while循環中。

我寫了一個簡單的例子,基於幾乎在此: python - Simulating 'else' in dictionary switch statements

import sys 

def mode1(arg = None): 
    return 'Mode1 completed' 

def mode2(arg = None): 
    return 'Mode2 completed' 

def mode3(arg = None): 
    return 'Mode3 completed' 

def modeQuit (arg = None): 
    sys.exit(0) 

def main(): 
    menuText = "Select mode, insert number of wanted mode: \n 1. first mode \n 2. second mode \n 3. Third mode\n" 

    # Function dictionary 
    mode_function = { 
     '1' : mode1, 
     '2' : mode2, 
     '3' : mode3, 
     'q' : modeQuit 
     } 

    data=None 

    print mode_function 

    while True: 
    mode_selection = raw_input(menuText).strip() 
    try: 
     print mode_function[mode_selection](data) 
    except KeyError: 
     print 'Not a valid mode' 

    return 0 

if __name__ == '__main__': 
    main();