[Tutor] Re: problem writing random_word function (original) (raw)
Matt Smith smith-matt at tiscali.co.uk
Mon Jul 19 18:40:44 CEST 2004
- Previous message: [Tutor] problem writing random_word function
- Next message: [Tutor] Re: problem writing random_word function
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Mon, 19 Jul 2004 11:13:11 -0400, Lloyd Kvam wrote:
You never initialized wordlist. See below.
You are better off simply appending to wordlist rather than maintaining your own counter. len(wordlist) 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 correctly.
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 == "": break elif len(word) == word_length: word_list = word_list + [word] f.close() return word_list[random.randint(0,(len(word_list)-1))]
Cheers, Matt.
- Previous message: [Tutor] problem writing random_word function
- Next message: [Tutor] Re: problem writing random_word function
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]