python运行方法后重启程序

Ste*_*son 0 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()
Run Code Online (Sandbox Code Playgroud)

如何在方法完成而不是程序终止后再次显示此菜单?

我以为我可以将整个程序包装成无限循环,但这感觉不对:P

Rus*_*ove 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()
Run Code Online (Sandbox Code Playgroud)

如果无限循环"感觉不对",问问自己何时以及为何应该结束.你有第三个输入选项退出循环吗?然后加:

if menu == "3":
    break
Run Code Online (Sandbox Code Playgroud)