Python menu-driven programming

Lbert Hartanto picture Lbert Hartanto · Aug 24, 2014 · Viewed 38.1k times · Source

For menu-driven programming, how is the best way to write the Quit function, so that the Quit terminates the program only in one response.

Here is my code, please edit if possible:

print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
while choice!="q":
    if choice=="v":
        highScore()
        main()
    elif choice=="s":
        setLimit()
        main()
    elif choice=="p":
        game()
        main()
    else:
        print("Invalid choice, please choose again")
        print("\n")
print("Thank you for playing,",name,end="")
print(".")

When the program first execute and press "q", it quits. But after pressing another function, going back to main and press q, it repeats the main function. Thanks for your help.

Answer

johntellsall picture johntellsall · Aug 24, 2014

Put the menu and parsing in a loop. When the user wants to quit, use break to break out of the loop.

source

name = 'Studboy'
while True:
    print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
    choice = raw_input(">>> ").lower().rstrip()
    if choice=="q":
        break
    elif choice=="v":
        highScore()
    elif choice=="s":
        setLimit()
    elif choice=="p":
        game()
    else:
        print("Invalid choice, please choose again\n")

print("Thank you for playing,",name)
print(".")