[英]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'.我正在制作一个基于文本的菜单,并希望在输入字母“q”时结束程序,但是我需要不止一次这样做(2 次或 3 次,我不确定为什么会这样)但我的时间如果输入为“q”,循环将停止。 Here is the function:
这是 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.我还没有定义每个字母的作用我只是想确保它会在按下“q”时停止。
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.
使用 userInput[0] 仅检查第一个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.