[Tutor] Re: problem writing random_word function
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.
I've rewritten the function as below and everything seems to work
"""Returns a random word of length word_length"""
f = open("hangman_words.txt","r")
word_list = 
word = f.readline()
word = word.strip()
if word == "":
elif len(word) == word_length:
word_list = word_list + [word]
More information about the Tutor