为什么一切都打印相同的字母等级?

时间:2014-08-01 23:35:45

标签: python python-3.4

我的任务是创建一个程序,打开并从文本文件中读取,计算成绩,包括平均权重,给出最终成绩,将其更改为字母等级,然后将其写入新的文本文件。一切都很好,直到将点数转换为字母等级。所有成绩都在70-89之间,所以我没有费心为A,B或E(F)添加任何其他代码。每当我尝试将成绩转换为字母等级时,它会将每个人的成绩改为C.我在哪里出错了?

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()  

2 个答案:

答案 0 :(得分:2)

因为您的if总是评估为真,因为它不按顺序排列。它应该是:

70 <= printedgrade <= 79

你的陈述总是评价为真,因为正如你所说的所有成绩都是70-89所以printedgrade大于或等于70而70小于79所以它总是{{1} }。

虽然我强烈建议让您的代码适用于所有等级。你不能假设,因为这个等级在他们总是会在一定的范围内。

答案 1 :(得分:1)

if printedgrade >= 70 <= 79:

应该是

if printedgrade >= 70 and printedgrade <= 79:

您还可以执行以下操作:

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