Reputation: 93
I have developed a program that puts a user's username, subject, unit, score and grade into a text file. This is the code:
tests.extend([subject, unit, str(score), grade])
print tests
with open("test.txt", "a") as testFile:
for test in tests:
userName = test[0]
subject = test[1]
unit = test[2]
score = test[3]
grade = test[4]
testFile.write(userName + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')
It prints:
['abc', 'history', 'Nazi Germany', '65', 'C']
('abc' being the username)
And the following error:
grade = test[4]
IndexError: string index out of range
I don't know why I'm getting this error? Any ideas?
*Already added in previously in quiz: *
quizzes = []
quizzes.append(userName)
Upvotes: 2
Views: 53
Reputation: 13498
In the for loop you are iterating through each word inside one test, not through each test in a list of tests. So, when you call test[0] or test[4], you are not indexing a characteristic of one test, but you are accidentally getting a character from a characteristic from one test. You can fix this by putting brackets around your tests array. For example:
Tests = [['abc', 'history', 'Nazi Germany', '65', 'C'],
['test2', 'python', 'iteration', '65', 'C']]
for username, subject, unit, score, grade in tests:
testFile.write(username + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')
Now you are iterating through each test within tests, not each characteristic within one test
Upvotes: 3