简体   繁体   中英

Random word generator in Python

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)
prompt = ""

This is a global variable.

def generate():
    global dict
    i = random.randint(0, 101824)
    prompt = word_list[i]
    return prompt

Because this code does not say global prompt , the global variable prompt is therefore not modified by prompt = word_list[i] .

while len(prompt) < 3:
    generate()

Each time through the loop, the value return ed by generate is ignored, because nothing is done with the value. len(prompt) continues to use the "" value from above, which is shorter than 3 characters; thus the loop cannot break.

You should not use a global variable for this . You should instead write code that actually uses the return value. For example:

prompt = generate()
while len(prompt) < 3:
    prompt = generate()

These lines would continue to work if put inside another function, because they take the value returned from generate() and give it a name that can be used locally.


Notice that generate does make use of the global variable word_list , despite that there also is no global word_list . You do get read-only access to global variables automatically. But if you have a local variable with the same name, it is used preferentially.

It's due to your while loop initialized to empty so the size is 0. Your generate function that you declared there is merely defining the function, and it doesn't get execute unless you call it. So you could call it once right before the while loop if you're intend to get generate to call before starting the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM