Test grade average python / n.append(float(score)) AttributeError: 'int' object has no attribute 'append'

Test grade average python / n.append(float(score)) AttributeError: 'int' object has no attribute 'append'

收到此错误:

n.append(float(score))
AttributeError: 'int' object has no attribute 'append'. 

在 运行 下面的代码之后:

def averageTestScore(n):
    total = 0
    for x in range(n):
        total += x #sum of numOf tests taken
        avg = total / len(str(n))
        for counter in range(0, n):
            score = float(input("What was your score on test # "))
            # n.append(float(score))
            # score += counter
        return avg

numberOfTests = int(input("How many tests did you take? "))
average = averageTestScore(numberOfTests)
print("The average of those test scores is:", average)

在上面给出的代码中,您试图将一个整数附加到另一个整数(注意 n 是您用作函数参数的测试次数,这就是为什么您得到错误).

我想你想要的是获得测试的平均值。

所以,我认为这可能对您有所帮助

def averageTestScore(n):
    tt=0
    for i in range(n):
        sc=float(input("What was your score on test : "))
        tt+=sc
    return tt/n
numberOfTests = int(input('How many tests did you take ? '))
average = averageTestScore(numberOfTests)
print("The average of those test scores is :", average)

将您的代码更改为 -

def averageTestScore(n):
    score = 0
    for num in range(1,n+1):
       score += float(input(f"What was your score on test {num} "))

    avg = score/n
    return avg

numberOfTests = int(input("How many tests did you take? "))
average = averageTestScore(numberOfTests)
print("The average of those test scores is:", average)

那么它应该可以正常工作。

您遇到错误,因为您不能追加到整数,只能追加到可以追加的列表。因此,尝试这种不同的方法。我使用了 f-strings 以便也显示测试编号。