2011-04-12 65 views
0

我想創建一個程序,它從txt文件中讀取多選答案,並將它們與設置的答案關鍵字進行比較。這是我迄今爲止的,但問題是,當我運行它時,答案在整個程序的整個生命週期中都停留在單個字母上。我已經在answerKey行之後放置了一個打印語句,並且它正確地打印出來,但是當它將「檢查」答案與答案鍵進行比較時,它會卡住並始終認爲「A」應該是正確的答案。這很奇怪,因爲它是我的示例應答鍵中的第三個條目。幫助在Python中創建考試分級程序

下面的代碼:

answerKey = open("answerkey.txt" , 'r') 
studentExam = open("studentexam.txt" , 'r') 
index = 0 
numCorrect = 0 
for line in answerKey: 
    answer = line.split() 
for line in studentExam: 
    studentAnswer = line.split() 
    if studentAnswer != answer: 
     print("You got question number", index + 1, "wrong\nThe correct answer was" ,answer , "but you 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! You passed!") 

感謝任何幫助,您可以給我!

+0

什麼的文本文件的格式? – 2011-04-12 09:05:03

+0

您的縮進是否正確? – eat 2011-04-12 09:05:11

+0

請提供示例輸入文件以及在使用這些輸入文件運行程序時獲得的輸出。 – 2011-04-12 09:09:11

回答

3

問題是你沒有正確地嵌套循環。

該循環首先運行,最後將answer設置爲answerKey的最後一行。

for line in answerKey: 
    answer = line.split() 

for line in studentExam:循環之後運行,但answer不會在這個循環變化,將保持不變。

該解決方案結合使用zip的循環:

for answerLine, studentLine in zip(answerKey, studentExam): 
    answer = answerLine.split() 
    studentAnswer = studentLine.split() 

此外,請記住,當你與他們進行關閉文件:

answerKey.close() 
studentExam.close() 
+1

非常感謝,程序正常工作!我欠你一杯啤酒 – Jmonge 2011-04-12 16:24:36

0

您在覆蓋for循環的每個迭代中覆蓋您的答案。答最有可能是答案的最後一項。嘗試將兩個for循環合併爲一個!

2

問題不在於您遍歷answerkey.txt中的所有行,然後最終將其最後一行僅與所有studentexam.txt行進行比較?