[Tutor] problem writing random_word function
Matt Smith
smith-matt at tiscali.co.uk
Mon Jul 19 14:21:57 CEST 2004
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")
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.
More information about the Tutor
mailing list