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

如何修改Python程序实现学生成绩计算与统计功能?

初始需求

编写程序输入单个学生的课程作业分和预考分,计算并显示其百分比和等级,计算公式为:Grade = ((coursework mark + prelim mark) * 100) / 150

修改需求
  • 从外部文件读取班级15名学生的姓名、课程作业分、预考分
  • 用「Count Occurrences」标准算法统计班级中A级(≥70%)的人数
  • 用「Find Max」标准算法找出班级中百分比最高的学生
等级划分规则
  • A级:百分比≥70%
  • B级:百分比60%-69%
  • C级:百分比50%-59%
  • D级:百分比45%-49%
  • 无等级:百分比<45%
现有代码
marks={59,33,55,10,47,60,57,45,20,39,55,25,23,30,54}

prelim={75,80,88,45,78,90,82,65,40,59,75,50,48,60,86}

name={Kevin,Anna,Paul,John,Anne,Frank,Susan,Mary,James,Katie,Mark,Stacey,Michael,Abdul,Kirsty}

def calculate():
  
  grade= ((marks[x] + prelim[x]) * 100 / 150)

  return 
    
for x in range (14):
  
  names= str(name[x])
  
  print( name, "has achieve", calculate, "percentage")
现有代码问题
  • 用集合{}存储数据错误,集合无序且无法通过索引访问对应学生的信息,需改用列表[]
  • 姓名未加引号,会被识别为变量而非字符串,直接触发报错
  • calculate函数无参数传入,也未返回计算结果,无法生成有效百分比
  • 循环range(14)仅遍历14个学生,漏掉了第15个(应使用range(15))
  • 打印语句直接输出整个集合name和函数对象calculate,而非对应学生的姓名与计算出的百分比
符合需求的完整实现

先准备外部数据文件students.txt,每行格式为姓名,课程作业分,预考分,示例内容:

Kevin,59,75
Anna,33,80
Paul,55,88
John,10,45
Anne,47,78
Frank,60,90
Susan,57,82
Mary,45,65
James,20,40
Katie,39,59
Mark,55,75
Stacey,25,50
Michael,23,48
Abdul,30,60
Kirsty,54,86

编写代码:

def calculate_percentage(coursework, prelim):
    return ((coursework + prelim) * 100) / 150

def determine_grade(percentage):
    if percentage >= 70:
        return "A级"
    elif 60 <= percentage < 70:
        return "B级"
    elif 50 <= percentage < 60:
        return "C级"
    elif 45 <= percentage < 50:
        return "D级"
    else:
        return "无等级"

# 读取文件中的学生数据
students = []
with open("students.txt", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        name, coursework_str, prelim_str = line.split(",")
        coursework = int(coursework_str)
        prelim = int(prelim_str)
        percentage = calculate_percentage(coursework, prelim)
        grade = determine_grade(percentage)
        students.append({
            "name": name,
            "percentage": percentage,
            "grade": grade
        })

# Count Occurrences统计A级人数
a_count = 0
for student in students:
    if student["grade"] == "A级":
        a_count += 1

# Find Max查找百分比最高的学生
max_percent = -1
top_student = None
for student in students:
    if student["percentage"] > max_percent:
        max_percent = student["percentage"]
        top_student = student

# 输出结果
print("班级学生成绩详情:")
for s in students:
    print(f"{s['name']}:{s['percentage']:.1f}%,等级{s['grade']}")

print(f"\n班级A级人数:{a_count}")
print(f"百分比最高的学生:{top_student['name']},成绩{top_student['percentage']:.1f}%")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:36:08