Python 使用空行作为指示符值,以结束while循环中的输入
我对Python还是新手。我的教授给了我们一个实验活动,它需要从用户的输入中打印出一个列表中的单词,而这个列表中的元素只在一次出现时才会显示。除了我不太确定教授用“空行”作为终止循环输入的指示值是什么意思外,其他一切都很好Python 使用空行作为指示符值,以结束while循环中的输入,python,python-3.x,while-loop,output,blank-line,Python,Python 3.x,While Loop,Output,Blank Line,我对Python还是新手。我的教授给了我们一个实验活动,它需要从用户的输入中打印出一个列表中的单词,而这个列表中的元素只在一次出现时才会显示。除了我不太确定教授用“空行”作为终止循环输入的指示值是什么意思外,其他一切都很好 word_Box = [] enter_Word = str(input("\nEnter a word. (Press 'Enter' key if finished.): \n")) #asking for user's 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键,则变量enter_Word=“”
因为这是循环的退出条件,所以循环将停止,程序将继续运行
word_Box = list(dict.fromkeys(word_Box))