list - Help creating exam grading program in Python -
i trying create program reads multiple choice answers txt file , compares them set answer key. have far problem that when run it, answer key gets stuck on single letter throughout life of program. have put print statement right after answerkey line , prints out correctly, when compares "exam" answers answer key gets stuck , thinks "a" should correct answer. weird because 3rd entry in sample answer key.
here's code:
answerkey = open("answerkey.txt" , 'r') studentexam = open("studentexam.txt" , 'r') index = 0 numcorrect = 0 line in answerkey: answer = line.split() line in studentexam: studentanswer = line.split() if studentanswer != answer: print("you got question number", index + 1, "wrong\nthe correct answer was" ,answer , "but answered", studentanswer) index += 1 else: numcorrect += 1 index += 1 grade = int((numcorrect / 20) * 100) print("the number of correctly answered questions:" , numcorrect) print("the number of incorrectly answered questions:" , 20 - numcorrect) print("your grade is" ,grade ,"%") if grade <= 75: print("you have not passed") else: print("congrats! passed!") thanks can give me!
the problem you're not nesting loops properly.
this loop runs first, , ends setting answer last line of answerkey.
for line in answerkey: answer = line.split() the for line in studentexam: loop runs afterwards, answer doesn't change in loop , stay same.
the solution combining loops using zip:
for answerline, studentline in zip(answerkey, studentexam): answer = answerline.split() studentanswer = studentline.split() also, remember close files when you're done them:
answerkey.close() studentexam.close()
Comments
Post a Comment