I was trying to randomly select a word from a word list. However, since the word list (from file:///usr/share/dict/words; Mac OS) contains almost every word, I wish to ignore those words containing 5 letters or less.
#Getting words from words.txt (retrieved from file:///usr/share/dict/words)
wordList = open(wordBank).readlines()
while True:
wordChosen = random.choice(wordList)
if len(wordchosen) > 5:
break
else:
xxxxxxxx
print wordChosen
How should I code the "else" part where it tells the computer to re-run the random selection until a word with more than 5 letters is found? Can it be performed by using if-else statements?
You actually don't need to put anything in the else block, and it can be safely removed. Due to the while loop with a True condition, your code will run until it finds a word longer than 5 characters long, at which point the loop will break (although it could potentially run forever!) and the word will be printed.