Reputation: 23
How do I fix the error my code comes up with the following?
Traceback (most recent call last):
File "main.py", line 143, in <module>
print(question_list2[random_int])
IndexError: list index out of range
This is the code in question:
question_list2 = []
question_list2.append(" the marines are ___ based opreatives ")
question_list2.append(" for under water travel marines use _____ ")
question_list2.append(" the avergae marine trains for _ weeks ")
answer_list2 = []
answer_list2.append("sea")
answer_list2.append("subamrines")
answer_list2.append("13")
top_index = 4
correct = 0
for i in range (0,4):
random_int = random.randint(0,top_index)
print(question_list2[random_int])
top_index = top_index - 1
user_answer1 = input("fill in the blank with the correct word ")
if user_answer == answer_list1[random_int]:
correct = correct + 3
del question_list1[random_int]
del answer_list1[random_int]
Upvotes: 0
Views: 67
Reputation: 51
I believe that you only have three things on your list. The range should be range(0,3) and maybe your top_index should be top_index = 2.
Since the indexes on your list are [0,1,2]
The first item in list > index = 0
The second item in list > index = 1
The third item in list > index = 2
Upvotes: 0
Reputation: 92440
From the random docs
random.randint(a, b)
Return a random integer N such that a <= N <= b
This means that:
top_index = 4
random_int = random.randint(0,top_index)
Has the possibility of setting random_int
to 3
or 4
which are outside the range of your list which only has three items with index 0
, 1
, and 2
.
Rather than mutating your lists and using indexes, it might be easier to make a list of indexes, shuffle it, then iterate over it:
indexes = random.sample(range(0, len(question_list)), k = len(question_list))
for i in indexes:
# etc...
If you kept the questions and answers together in a single list, you could do away with the indexes altogether. This would be a good use for named tuples
import random
from collections import namedtuple
qa = namedtuple('QA', ['question', 'answer'])
question_list = [
qa(" the marines are ___ based opreatives ", 'sea'),
qa(" for under water travel marines use _____ ",'submarines'),
qa(" the avergae marine trains for _ weeks ", '13')
]
random.shuffle(question_list)
correct = 0
for qa in question_list:
print(qa.question)
user_answer = input("fill in the blank with the correct word ")
if user_answer == qa.answer:
correct = correct + 1
Upvotes: 2