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

Python列表存储学生成绩触发IndexError索引越界错误解决方法

错误原因

  • range(0,4)仅会生成0、1、2、3四个整数,循环仅执行4次,无法完成5名学生的成绩录入,要录入5个学生需要改成range(5)(生成0-4共5个整数)
  • 你初始化的student列表长度仅为3,当循环变量i≥3时,执行student[i] = ...操作就会触发索引越界错误。这个列表的设计逻辑存在问题,你不需要用它存储所有学生的成绩集合,每次循环生成单个学生的成绩列表后直接存入目标列表midterm_score即可。

优化后可运行代码

推荐使用列表append()方法实现,不需要预先给列表设置占位值,灵活度更高:

midterm_score = []
# 循环5次录入5名学生成绩
for i in range(5):
    print(f"Enter Student {i+1}'s Sociology Score: ")
    soc_score = int(input())
    print(f"Enter Student {i+1}'s Algebra Score: ")
    alg_score = int(input())
    print(f"Enter Student {i+1}'s English Score: ")
    eng_score = int(input())
    # 直接追加当前学生的成绩列表到目标列表
    midterm_score.append([soc_score, alg_score, eng_score])
print(midterm_score)

原写法修复方案

如果你坚持使用预先初始化列表的思路,调整初始列表长度和循环范围即可:

# 初始化长度为5的列表存储5个学生的成绩
student = [0]*5
for i in range(5):
    print("Enter Student " + str(i+1) + "'s Sociology Score: ")
    Soc_score = int(input())
    print("Enter Student " + str(i+1) + "'s Algebra Score: ")
    Alg_score = int(input())
    print("Enter Student " + str(i+1)+"'s English Score: ")
    Eng_score = int(input())
    student[i] = [Soc_score, Alg_score, Eng_score]
midterm_score = student
print(midterm_score)

内容的提问来源于stack exchange,提问作者J.Moon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:54:03