You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python计算考试平均分执行n.append(float(score))报int无append属性如何解决

报错原因

你调用averageTestScore函数时传入的参数n是用户输入的考试科目数,属于整数(int)类型,而append()是Python列表(list)专属的新增元素方法,整数类型本身没有这个方法,调用就会触发该报错。

除此之外你现有代码的逻辑也存在多处问题:

  • 累加变量total加的是循环变量x的取值(1、2、...n),不是实际录入的考试分数
  • 写了两层重复的循环,会导致重复录入成绩
  • 平均分计算逻辑total / len(str(n))错误,不符合「总分数÷考试数量」的计算规则
修复方案

删除冗余逻辑,按需求直接累加分数计算平均分即可,两种参考实现如下:

方案1:直接累加分数(性能更高)

def averageTestScore(n):
    total_score = 0
    for counter in range(n):
        score = float(input(f"What was your score on test #{counter+1}? "))
        total_score += score
    avg = total_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)

方案2:用列表存储所有成绩(方便后续对成绩做其他处理)

def averageTestScore(n):
    scores = []
    for counter in range(n):
        score = float(input(f"What was your score on test #{counter+1}? "))
        scores.append(score)
    avg = sum(scores) / len(scores)
    return avg

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

内容的提问来源于stack exchange,提问作者Tyree Rochelle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 03:45:02