2016-09-04 195 views
1
def Commands(): 
      command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':") 
      elif command == "Run" : 
       restart = True 
       break 
if groups == 4 : 
    restart = True 
    while restart : 
     restart = False 
     Commands() 

如何讓此函數正常工作? 「restart = True」「break」行不會再次啓動前一個「while」循環。我在多個「if」語句中使用這些命令,並希望避免爲每個代碼重複使用80多行代碼。我刪除了無關的代碼,正常工作。作爲函數嵌套'While'循環

+0

如果沒有'if',你就不能有'elif'。從你的'commands()'函數返回'True'或'False',並用它來確定你是否應該重新啓動。 – khelwood

+0

我有,如果ELIF和其他,我刪除他們,因爲他們工作正常,並希望保持短代碼,並專注於重啓的問題,並打破不啓動外'while'循環 – Miller

回答

3

,而不是試圖use a global variable或循環外的break(目前的使用情況應該給一個語法錯誤) - 你應該return一個布爾值,評估函數的返回值,如:

def Commands(): 
    command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':") 
    if command.lower() == "run" : 
     return True 
     # changed this to use lower (so it sees run or Run or RUn) 
     # and now it just returns a True value to say - keep going 
    return False 
    # assuming that everything else means break out of loop just return False if not "Run" 

while True: 
    if not Commands(): 
     break 

print "We're out" 

你也可以只設置while循環while Commands():並刪除breakthis answer to a related question

0

當函數由於超出範圍而返回時,變量重新啓動不成立。一個簡單的解決方案可能只是讓Commands()返回true或false值並在while循環中重新啓動指定的值。

restart = Command() #Where command returns true or false 

Short Description of the Scoping Rules?

0

這是最簡單的使用返回值。如果你想進一步消除樣板,你可以使用例外:

def Commands(): 
    command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':") 
    if command != "Run" : 
     raise StopIteration 
if groups == 4 : 
    try: 
     while True: 
      Commands() 
    except StopIteration: 
     print('Done')