python - 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
解决方案
当在循环内到达这条线时
enter_Word = str(input("\nEnter a word (Press 'Enter' key if finished.): \n"))
如果按下回车键,则变量 enter_Word = “”</p>
因为这是循环的退出条件,所以循环将停止,程序将继续执行
word_Box = list(dict.fromkeys(word_Box))
推荐阅读
- css - 订购 flexbox 元素使容器无法填满屏幕
- c# - WPF DataGrid 中的空行
- c++ - C++ 可变参数模板空参数特化
- python - 从python中的模块导入__main__
- python - python更新列表中字典的每个键值
- php - Jquery datatable Invalid Argument exception - 消息 - Laravel eloquent raw query 上的尾随数据
- android - 安装STF,没有那个文件或目录,uv_chdir
- lua - Lua获取该函数附加到的表
- python - LSTM 的贝叶斯优化
- microsoft-graph-api - 使用 Microsoft Graph 将文件上传到 onedrive,遇到问题“UnknownErorr”无法检索用户的 mysite URL