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
2 个回答
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()
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