Emrys
Emrys

Reputation: 5

Why does this print same letter grade for everything?

My assignment is to create a program that opens and reads from a text file, calculates grades, including average weights, gives a final grade, changes it to a letter grade, and then writes it into a new text file. Everything has worked fine up until the conversion of the points to letter grades. All grades are between 70-89, so I haven't bother putting any other code for A,B, or E(F). Whenever I try to convert the grade to letter grade, it changes everyone's grade to a C. Where have I went wrong?

infile = open("c:\\Python34\\MyFiles\\ClassGradebook.txt","r")  
outfile = open("c:\\Python34\\myfiles\\ClassGrades.txt","w") 

aline = infile.readline()  # uses readline method to read the first line of the file

def quizsum():
        quizsum1 = quiz1 + quiz2 + quiz3
        quizavg = (quizsum1 / 30) * .3
        return float(quizavg)

def midtermsum():
        midtermsum1 = midterm1 + midterm2
        midtermavg = (midtermsum1 / 200) * .4
        return float(midtermavg)

def finalsum():
        finalsum1 = final1
        finalavg = (finalsum1 / 100) * .3
        return float(finalavg)
def lettergrade():
        if printedgrade >= 70 <= 79:
                return "C"
        else:
                return "B"       

while aline:
        items = aline.split()   
        dataline = items[0] + " " + items[1] 
        quiz1 = int(items[2])
        quiz2 = int(items[3])
        quiz3 = int(items[4])
        midterm1 = int(items[5])
        midterm2 = int(items[6])
        final1 = int(items[7])
        quizavg = quizsum()
        midtermavg = midtermsum()
        finalavg = finalsum()
        gradetotal = quizavg + midtermavg + finalavg
        printedgrade = gradetotal * 100
        printedgrade2 = lettergrade()
        print(dataline)
        print(printedgrade2)
        outfile.write(printedgrade2 + '\n')   newline character
        aline = infile.readline()   

infile.close()  
outfile.close()  

Upvotes: 0

Views: 95

Answers (2)

kylieCatt
kylieCatt

Reputation: 11039

Because your if is always evaluating true because it's out of order. It should be:

70 <= printedgrade <= 79

Your statement is always evaluating as true because as you said all the grades are 70-89 so printedgrade will be greater than or equal to 70 and 70 is less than 79 so it will always be True.

Although I would strongly suggest making your code work for all grades. You can't assume because this time the grades are in a certain range that they always will be.

Upvotes: 2

Tom Dalton
Tom Dalton

Reputation: 6190

if printedgrade >= 70 <= 79:

should be

if printedgrade >= 70 and printedgrade <= 79:

You could also do something like:

if printedgrade >= 90:
    return "A"
elif printedgrade >= 80:
    return "B"
elif printedgrade >= 70:
    return "C"
...

Upvotes: 1

Related Questions