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:
you need use
wordlist[words]each time want word; never interested in random integer, there no point in storing that. butwords = wordlist[random.randint(0, len(wordlist))]is rather more verbose
random.choice()alternative.random.randint()picks number between start , stop values, inclusive. means can end pickinglen(wordlist), there no such index inwordlistlist; you'dindexerror. need userandom.randint(0, len(wordlist)) - 1, really, or perhapsrandom.randrange(len(wordlist))instead.but again,
random.choice()easier.
Comments
Post a Comment