[Tutor] problem writing random_word function

Lloyd Kvam pythonTutor at venix.com
Mon Jul 19 17:13:11 CEST 2004


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.


On Mon, 2004-07-19 at 08:21, Matt Smith wrote:
> Hi,
> I'm attempting to write a function that returns a random word of a
> specified length for use in a hangman game.  The source of the words is a
> text file with each word on a new line.  I got the function working
> printing all of the words of the desired length.  I now want to make a
> list of all the words of the correct length then pick a random item from
> the list.  Here is the function and traceback:
> 
> 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:
>         n = 0
>         text = f.readline()
>         text = text[0:len(text)-2]
>         if len(text) == word_length:
>             word_list[n] = text
>             n = n+1
>     f.close()
>     return word_list[random.randint(0,n)]
> 
> Traceback (most recent call last):
>   File "/home/matt/hangman.py", line 15, in -toplevel-
>     print random_word(5)
>   File "/home/matt/hangman.py", line 9, in random_word
>     word_list[n] = text
> NameError: global name 'word_list' is not defined
> 
> Hope you can help,
> Matt.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582



More information about the Tutor mailing list