1

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.

Lbert Hartanto
  • 131
  • 2
  • 2
  • 6

4 Answers4

5

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(".")
johntellsall
  • 14,394
  • 4
  • 46
  • 40
1
 def Menu:
     while True:
          print("1. Create Record\n2. View Record\n3. Update Record\n4. Delete Record\n5. Search Record\n6. Exit")
          MenuChoice=int(input("Enter your choice: "))
          Menu=[CreateRecord,ViewRecord,UpdateRecord,DeleteRecord,SearchRecord,Exit]
          Menu[MenuChoice-1]()
0

You're only getting input from the user once, before entering the loop. So if the first time they enter q, then it will quit. However, if they don't, it will keep following the case for whatever was entered, since it's not equal to q, and therefore won't break out of the loop.

You could factor out this code into a function:

print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()

And then call it both before entering the loop and then as the last thing the loop does before looping back around.

Edit in response to comment from OP:

The following code below, which implements the factoring out I had mentioned, works as I would expect in terms of quitting when q is typed.

It's been tweaked a bit from your version to work in Python 2.7 (raw_input vs. input), and also the name and end references were removed from the print so it would compile (I'm assuming those were defined elsewhere in your code). I also defined dummy versions of functions like game so that it would compile and reflect the calling behavior, which is what is being examined here.

def getChoice():
    print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
    choose=raw_input(">>> ")
    choice=choose.lower()

    return choice

def game():
    print "game"

def highScore():
    print "highScore"

def main():
    print "main"

def setLimit():
    print "setLimit"


choice = getChoice()

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

    choice = getChoice()

print("Thank you for playing,")
khampson
  • 14,700
  • 4
  • 41
  • 43
0

This is a menu driven program for matrix addition and subtraction

  def getchoice():
        print('\n What do you want to perform:\n 1.Addition\n 2. Subtraction')
        print('Choose between option 1,2 and 3')
        cho = int(input('Enter your choice : '))
        return cho


    m = int(input('Enter the Number of row    : '))
    n = int(input('Enter the number of column : '))
    matrix1 = []
    matrix2 = []

    print('Enter Value for 1st Matrix : ')
    for i in range(m):
        a = []
        for j in range(n):
            a.append(int(input()))
        matrix1.append(a)
    print('Enter Value for 2nd Matrix : ')
    for i in range(m):
        a = []
        for j in range(n):
            a.append(int(input()))
        matrix2.append(a)
    choice = getchoice()
    while choice != 3:
        matrix3 = []
        if choice == 1:
            for i in range(m):
                a = []
                for j in range(n):
                    a.append(matrix1[i][j] + matrix2[i][j])
                matrix3.append(a)
            for r in matrix3:
                print(*r)
        elif choice == 2:
            for i in range(m):
                a = []
                for j in range(n):
                    a.append(matrix1[i][j] - matrix2[i][j])
                matrix3.append(a)
            for r in matrix3:
                print(*r)
        else:
            print('Invalid Coice.Please Choose again.')

        choice = getchoice()