python运行方法后重新启动程序

python运行方法后重新启动程序

问题描述:

我确定有一个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

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

无限循环是这样做虽然方式是这样的:

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