首页 > 解决方案 > Using a blank line as an indicator value to end the input in while loop

问题描述

I am still new to Python. My professor gave us a lab activity that needs to print words in a list from the user's input that does not duplicate its elements which are only displayed in one occurence. Everything works well except I am not quite sure by what our professor means by having a "blank line" as an indicator value to terminate the looping input.

word_Box = []                 

enter_Word = str(input("\nEnter a word. (Press 'Enter' key if finished.): \n")) #asking for user's input'

while enter_Word != "": #asks for input until user does not have input/pressing Enter key in keyboard
        word_Box.append(enter_Word) #stores every inputted word at the end of the list
        enter_Word = str(input("\nEnter a word (Press 'Enter' key if finished.): \n"))

word_Box = list(dict.fromkeys(word_Box)) #elements of the list is converted to keys of a dictionary to remove duplicates as dictionaries don't allow duplicates
                                                                         #dictionary is converted back to a list

print("\nThe word/s you entered is/are: ", word_Box)   #prints all the elements                                                       

标签: pythonpython-3.xwhile-loopoutputblank-line

解决方案


当在循环内到达这条线时

enter_Word = str(input("\nEnter a word (Press 'Enter' key if finished.): \n"))

如果按下回车键,则变量 enter_Word = “”</p>

因为这是循环的退出条件,所以循环将停止,程序将继续执行

word_Box = list(dict.fromkeys(word_Box))

推荐阅读