Edit: made some changes - now the program finishes, but still doesn't output anything.
import random
dict = open("british-english")
word_list = dict.readlines()
def generate():
global word_list
prompt = random.choice(word_list)
if len(prompt) < 3:
generate()
else:
return prompt
generate()
print(prompt)
I have written the below code to try and generate a random word of three letters or more from the brisih-english text file I found on my linux machine. I have copied the file to the same directory as my .py file. When I run the program in the terminal, I get no output, but the program seems to run infinitely. I am still a beginner at this, but this seems like such a simple program that I wonder what I could be missing. I already ran some tests to print different elements of the list to make sure I could access the words, which worked fine.
import random
#list contains 101,825 elements
dict = open("british-english")
word_list = dict.readlines()
prompt = ""
def generate():
global dict
i = random.randint(0, 101824)
prompt = word_list[i]
return prompt
while len(prompt) < 3:
generate()
print(prompt)
global dictdo insidegenerate? Taking that into consideration, when the conditionlen(prompt) < 3is checked, what do you expect the value ofpromptto be, and why? What is that value'slen?word_listelements randomly, just userandom.choice. That way, you don't have to worry about how long the list is, and the code won't break if the file changes. Also, instead of repeating until you find a long enough word, you could just remove the short words from the list first.global prompt? Therefore, doesgenerateaccess the global variableprompt? Now, what about the while loop? Is it inside a function? Therefore, is it using the global variable?