简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM