我试图使用while循环从文本文件中的列表中打印单词。我需要循环停止,一旦它达到4个字符长的单词。用我目前的代码,我得到了一个无限循环。使用while循环打印列表中的单词,直到打印出长度为4的单词为止
wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()
# While loop displays names based on length of words in list
print("\nSelected words are:")
while words in wordList:
if len(words) != 4:
print(words)
样品所需的输出
选择的话是:
阿巴特
强辩
推广开
的反驳
潜
异常
凝结
溶解
贫嘴
发布问题时,应尽量从不相关的细节中尽可能地隔离代码中的问题。在这种情况下,单词列表的来源与根据长度从列表中打印单词的动作无关。 –