2010-12-10 38 views
0

我確定有一個noob問題。例如,假設我有一個看起來像這樣的程序。python運行方法後重新啓動程序

def method1(): 
    #do something here 

def method2(): 
    #do something here 

#this is the menu 
menu=input("What would you like to do?\ntype 1 for method1 or 2 for method2: ") 
if(menu=="1"): 
    method1() 
if(menu=="2"): 
    method2() 

如何讓該菜單在方法結束而不是程序終止後再次出現?

我想我可以包住整個程序進入一個死循環,但感覺不對:P

+0

我會用一個無限循環做(或不無休止的,這取決於其他任何你正在做)。 – rovaughn 2010-12-10 22:19:41

+0

包裝它非無限循環是否有退出程序的選擇。 – 2010-12-10 22:19:56

回答

5
while True: 
    #this is the menu 
    menu=input("What would you like to do?\ntype 1 for method1 or 2 for method2: ") 
    if(menu=="1"): 
     method1() 
    if(menu=="2"): 
     method2() 

如果死循環「感覺不對」,問自己何時爲什麼它應該結束。你應該有第三個輸入選項退出循環?然後加入:

if menu == "3": 
    break 
+0

非常感謝。我會把整個事情放在循環,方法和一切中xD – 2010-12-10 22:33:04

+0

嗯......你永遠不會真的想把「整個程序」包裝在一個循環中;你想要在循環中**需要循環的部分**。 :) – 2010-12-10 23:49:11

0

無限循環是這樣做雖然方式是這樣的:

running = true 

def method1(): 
    #do something here 

def method2(): 
    #do something here 

def stop(): 
    running = false 

while running: 
    #this is the menu 
    menu=input("What would you like to do?\ntype 1 for method1 or 2 for method2 (3 to stop): ") 
    if(menu=="1"): 
     method1() 
    if(menu=="2"): 
     method2() 
    if(menu=="3"): 
     stop() 
+0

Russels方法比這更好 – Pengman 2010-12-10 22:26:06

相關問題