0

A noob question I'm sure. For example, say I have a program that looks something like this.

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()

How can I make this menu appear again after a method has finished instead of the program terminating?

I was thinking I could wrap the whole program into an endless loop, but that doesn't feel right :P

2
  • I'd do it with an endless loop (or not endless, depending on whatever else you're doing). Commented Dec 10, 2010 at 22:19
  • Wrap it non-endless loop were there is choice to exit the program. Commented Dec 10, 2010 at 22:19

2 Answers 2

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 the endless loop "doesn't feel right", ask yourself when and why it should end. Should you have a third input option that exits the loop? Then add:

if menu == "3":
    break
Sign up to request clarification or add additional context in comments.

2 Comments

thanks this is great. I was gonna put the whole thing inside the loop, methods and everything xD
Well... you never really want to wrap "the whole program" in a loop; you want to wrap the part that needs to loop in a loop. :)
0

An endless loop is the way to do it though, something like this:

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()

1 Comment

Russels method is better than this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.