简体   繁体   中英

List index out of range (python)

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)

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM