-1

I'm Writing a code, where the user can input one option out of a multiple choice selection. Whatever answer they give, such as "a" or "b", gets written as either "Correct" or "Not Correct" into a separate text file, (StudentAnswers.txt). Obviously, the new text file will be filled with multiple lines of "Correct", and "Incorrect"

This part has already been achieved, but can someone please show me how to create a code which reads the text file "StudentAnswers", and if the total number of recurring "Correct" values is greater or equal to half, print "Passed", or if not print "Fail"

Hope you guys Understand. Thanks.

Ash
  • 25
  • 4

1 Answers1

0

You can read the file lines and filter them either for "Correct" or for "Not Correct".

lines = open(file).readlines()
total = len(lines)
totalOK = len(filter( lambda x: x == "Correct\n") lines)
if totalOK >= total / 2:
    print "Passed"
else:
    print "Failed"

If you are not familiar with lambda and filter you can do it this way:

def countOK ( lines ):
    cnt = 0
    for i in lines:
        if i == "Correct\n":
            cnt += 1
    return cnt
...
lines = open( file ).readlines()
total = len( lines )
totalOK = countOK (lines)
if totalOK >= total / 2:
    print "Passed"
else:
    print "Failed"
Gabriel Ciubotaru
  • 1,042
  • 9
  • 22
  • Thanks for the reply, but when I run the code, even with the text "Incorrect Answer" inside the (StudentResponse) text file, it says "passed". Would you happen to know why and how to fix it? – Ash May 12 '15 at 12:50
  • Ah sorry man, your code worked fine, I just realized that only one line, either "Correct or Incorrect" will always produce a "Passed" – Ash May 12 '15 at 12:52
  • @Ash Glad i could help, you are weolcome. – Gabriel Ciubotaru May 12 '15 at 13:23