Creating a program that compares test scores to answers

Hey guys, so the issue I’m having is the program I’ve written seems to kind of do what it’s intended to do. The problem, though, is that I can’t seem to get it to compare the answers correctly, resulting in false scores.

def Main():

    total = 0
    answers = ['A','C','A','A','D','B','C','A','C','B','A','D','C','A','D','C','B','B','D','A']

    infile = open('Scores.txt', 'r')
    student_answers = infile.readline()

    for answer in student_answers:
        for S in range(len(answer)):
            if answer[S] == answers[S]:
                total += 1

    print('Total correct answers: ', total)
    print('Total of incorrect answers: ', 20 - total)

    if total >= 15:
            print('Congratulations! You passed the exam.')
    elif total < 15:
            print('Sorry, you have failed the exam.')

What’s happening is when answers which are the answer key, are compared to the answers in the Scores.txt file, it keeps giving me 7 correct and 13 wrong even if the file has the same answers as the answer key. It seems to be counting only the A’s as correct, as there are 7 of those in the answers list.

Any and all help is appreciated thank you.

What does Scores.txt look like? I would guess something like “ACAADBC…”, since you’re calling readline() once and then iterating over the resulting string.

In any event, let’s assume you have student_answers that is an iterable of one-character strings (whether that’s a string or a list of strings). And let’s further assume that the answers are all correct.

This loop will proceed as follows:

answer S answers[S] answer[S] answer[S] == answers[S]
"A" 0 "A" "A" True
"C" 0 "A" "C" False
"A" 0 "A" "A" True
"A" 0 "A" "A" True
"C" 0 "A" "D" False

Your outer loop seems fine, but your inner loop is just always a range(1). And while I’m sure there’s a way to do this with a nested loop, it will almost certainly be doing more work than you really need.

I think the zip() builtin function could be useful here.

1 Like

Assuming that the Score.txt file is ACAADBCACBADCADCBBDA, you can create a student_answers list object with student_answers = [answer for answer in infile.readline()]

Also, you don’t need a nested loop:

for index, _ in enumerate(answers):
        if student_answers[index] == answers[index]:
            total += 1

or even better:

for student, correct in zip(students_answers, answers):
    if student == correct:
        total += 1

To be really cleaver, you could take advantage of TRue being of value 1:

total += student == correct

But I really don’t like that – a bit too magic :slight_smile:

BTW: basic "print debugging is a critical skill tyr adding a print to your code:

    for answer in student_answers:
        for S in range(len(answer)):
            print(answer[S], answers[S])
            if answer[S] == answers[S]:
                total += 1

and you’d probably see the issue, if not the solution …