[Tutor] Re: problem writing random_word function

Matt Smith smith-matt at tiscali.co.uk
Mon Jul 19 18:40:44 CEST 2004

On Mon, 19 Jul 2004 11:13:11 -0400, Lloyd Kvam wrote:

> You never initialized word_list.  See below.
> You are better off simply appending to word_list rather than maintaining
> your own counter.  len(word_list) will tell you how many entries are
> present when you go to choose a random word.  Also, text.strip() will
> discard the line mark and is portable across operating systems. 
> Stripping the last two characters assumes that you are running with an
> OS that uses two character line marks.

Thanks Lloyd,
I've rewritten the function as below and everything seems to work

def random_word(word_length):
    """Returns a random word of length word_length"""
    import random
    f = open("hangman_words.txt","r")
    word_list = []
    while 1:
        word = f.readline()
        word = word.strip()
        if word == "":
        elif len(word) == word_length:
            word_list = word_list + [word]
    return word_list[random.randint(0,(len(word_list)-1))]


More information about the Tutor mailing list