Why do I need to input 'q' more than once to quit the while loop?

Question:

I am making a text-based menu and wanted to have the program end when the letter ‘q’ is inputted however I need to do it more than once (2 or 3, I am not sure why it can be either) yet my while loop will stop if the input is ‘q’.
Here is the function:

    userInput = input("Enter a letter to choose an option: n e - n r - n p - n h - n m - n s - n q - n")
    while userInput != 'q':
        if userInput == 'e':
            print("e has been pressed")
        if userInput == 'r':
            print("r has been pressed")
        if userInput == 'p':
            print("p has been pressed")
        if userInput == 'h':
            print("h has been pressed")
        if userInput == 'm':
            print("m has been pressed")
        if userInput == 's':
            show_preferences(userName, userDict)
        if userInput == 'q':
            print("q has been pressed")
        userInput = input("Enter a letter to choose an option: n e - Enter preferences n r - Get recommendations n p - Show most popular artists n h - How popular is the most popular n m - Which user has the most likes n s - show the current users' prefernces n q - Save and quit n")

I haven’t defined what each letter does I just want to make sure that it will stop when ‘q’ is pressed.

Asked By: Cr3 D

||

Answers:

userInput = ""
while userInput != 'q':
    userInput = input("Enter a letter to choose an option: n e - n r - n p - n h - n m - n s - n q - n")
    if userInput == 'e':
        print("e has been pressed")
    elif userInput == 'r':
        print("r has been pressed")
    elif userInput == 'p':
        print("p has been pressed")
    elif userInput == 'h':
        print("h has been pressed")
    elif userInput == 'm':
        print("m has been pressed")
    elif userInput == 's':
        show_preferences(userName, userDict)
    elif userInput == 'q':
        print("q has been pressed. Exit!")

You can use this version. Hope this helps.

To handle input of more than one character. Use userInput[0] to check the first character only.

Answered By: ysethi92
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.