无法将int对象转换为str隐式错误

时间:2014-02-26 05:14:33

标签: python

以下是我的代码的简化快照:

def getExamPoints(examPoints):
    totalexamPoints = 0 
    return totalexamPoints

def getHomeworkPoints(hwPoints):
    totalhwPoints = 0
    return totalhwPoints

def getProjectPoints(projectPoints):
    totalprojectPoints = 0
    return avgtotalprojectPoints

def computeGrade(computeGrade):
    computeGrade = 1
    return computeGrade

def main ( ):

    gradeReport = "\n\nStudent\t Score\tGrade\n=====================\n"

    studentName = input ("Enter the next student's name, or 'quit' when done: ")

    while studentName != "quit":

        examPoints = getExamPoints(studentName)
        hwPoints = getHomeworkPoints(studentName)
        projectPoints = getProjectPoints(studentName)

        studentScore = examPoints + hwPoints + projectPoints

        studentGrade = computeGrade (studentScore)

        gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore + "\t" + studentGrade** 

main ( ) # Start program

在最后一行的gradeReport赋值上出现错误,上面写着“无法将int对象隐式转换为str”。为什么会这样?

1 个答案:

答案 0 :(得分:2)

这是有问题的一行:

gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore+"\t"+studentGrad

您应该使用字符串格式而不是简单地将字符串和整数一起添加(这是一个错误)。一种方法是:

gradeReport = '%s\n%s\t%6.1f\t%s' % (gradeReport, studentName, studentScore, studentGrade

还有其他方法,但由于您已经使用%格式,我已经继续使用


在Python中,"5" + 5是一个错误,因为它不明确。它应该返回"55"吗? 10?而不是一半时间做出假设和错误,Python要求你明确它。