2

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)

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

alright i edited, just reply if you still have questions
Yep that's it working now. Thanks for the answer and explanation!

Your Answer

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.