0

I am creating a word generator for playing charades, and it works for about six words, then says "List index out of range."

this is my code:

def selection(word):
 while True:
 from random import randint
 sel = randint(1,10)
 print(word[sel])
 input("\nPress enter to select a new word.")
print("Type in ten words to add to the list.")
words = []
words.append(input("1st word: "))
words.append(input("2nd word: "))
words.append(input("3rd word: "))
words.append(input("4th word: "))
words.append(input("5th word: "))
words.append(input("6th word: "))
words.append(input("7th word: "))
words.append(input("8th word: "))
words.append(input("9th word: "))
words.append(input("10th word: "))
input("\nPress enter to randomly select a word.")
selection(words)
Artsiom Rudzenka
29.3k5 gold badges36 silver badges53 bronze badges
asked Nov 11, 2012 at 23:09
1
  • is there any specific reason you're importing randint repeatedly in the loop? Commented Nov 11, 2012 at 23:17

2 Answers 2

6

You are currently picking a number between 1 and 10, inclusive. Python lists are 0 indexed, so you should be picking a number between 0 and 9.

sel = randint(0, 9)

This is also a good place to use the choice() function. It picks a random element from a sequence (eg a list).

random_word = random.choice(words)
answered Nov 11, 2012 at 23:11

2 Comments

Also, if I wanted to make it so that the user could type in any number of words, how would I make it only select one of those words instead of one between 1 and some specified number?
@CharlieKimzey, random.choice. Notice you can just pass a list of words. You don't need to tell choice how many words there are.
0

Also, not really an answer but you can do

for i in xrange(0, 9):
 words.append(input("{0}st word: ".format(i + 1))

Also

random.choice

answered Nov 11, 2012 at 23:12

3 Comments

Could you please explain what that does?
will not work - since generate values from 0 to 8 including - 9 will be missed
This will print lines like "2st word"

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.