python - How to print a word in a list which has been assigned a random number? -


i wondering if me problem. in piece of code working on, creating game upon user guesses word list imported text file in python 3.3. choose random word list e.g

words = random.randint(0,len(wordlist)) 

i have successfully, got program working, when user gets word wrong, prints random number assigned not word list. example

else:     print("no, answer was",words) 

i wondering how print word list not random number?

don't use random number @ all. use random.choice() function instead:

words = random.choice(wordlist) 

random.choice() picks random item list.

your use of random.randint() has 2 problems:

  1. you need use wordlist[words] each time want word; never interested in random integer, there no point in storing that. but

    words = wordlist[random.randint(0, len(wordlist))] 

    is rather more verbose random.choice() alternative.

  2. random.randint() picks number between start , stop values, inclusive. means can end picking len(wordlist), there no such index in wordlist list; you'd indexerror. need use random.randint(0, len(wordlist)) - 1, really, or perhaps random.randrange(len(wordlist)) instead.

    but again, random.choice() easier.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -