string index out of range error using lists and text files (using Python)

238
December 31, 2017, at 10:45 AM

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)
Answer 1

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

Rent Charter Buses Company
READ ALSO
Django: The SECRET_KEY setting must not be empty. after importing views to settings.py

Django: The SECRET_KEY setting must not be empty. after importing views to settings.py

I am trying to add the following to LOGIN_REDIRECT_URL within the settings file basepy

369
DB Design Best Practice: Return multiple rows with individual entries, or single row with multiple entries?

DB Design Best Practice: Return multiple rows with individual entries, or single row with multiple entries?

I'm looking to put together a matrix for both skills and education detailsI'll have columns:

164
SQL for buy and sells summary and balance

SQL for buy and sells summary and balance

I have two tables for cryptocurrency trades history

166