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

新手求教:这段Python代码如何找出列表中的最高分?

逐步骤解析找出学生最高分的Python代码逻辑

我正在Udemy平台学习Angela Yu的课程,她讲解了以下代码,但作为编程新手,我无法理解这段代码是如何找出输入列表中的最高分的,希望有人能逐步骤解析代码逻辑。

# 🚨 不要修改下面的代码 👇
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
  student_scores[n] = int(student_scores[n])
print(student_scores)
# 🚨 不要修改上面的代码 👆

# 在这行下面写你的代码 👇

highest_score = 0

for score in student_scores:
    if score > highest_score:
        highest_score = score

print(score) # 注:这里应该写print(highest_score)才能输出最高分

第一部分:固定输入处理代码解析

  • student_scores = input("Input a list of student scores ").split()
    获取用户输入的一串以空格分隔的分数字符串,用split()方法按空格切割成字符串列表。比如输入"90 85 95 70",会得到["90", "85", "95", "70"]。
  • for n in range(0, len(student_scores)): + student_scores[n] = int(student_scores[n])
    遍历列表的每个索引位置,把列表里的每个字符串元素转换成整数类型——因为字符串没法直接比较大小,转成整数后才能进行数值对比。上面的例子会变成[90, 85, 95, 70]。
  • print(student_scores)
    打印转换后的整数列表,用来确认输入的分数已经被正确处理成可计算的数值。

第二部分:找最高分的核心逻辑解析

  • highest_score = 0
    初始化一个变量用来记录当前找到的最高分,默认设为0(这里默认分数都是非负的,符合学生分数的常规场景)。
  • for score in student_scores:
    逐个取出列表里的每一个分数,进行遍历检查。
  • if score > highest_score: + highest_score = score
    把当前遍历到的分数和highest_score对比:
    1. 第一个分数90 > 0,所以把highest_score更新为90;
    2. 第二个分数85 < 90,不更新;
    3. 第三个分数95 > 90,把highest_score更新为95;
    4. 第四个分数70 < 95,不更新;
      遍历结束后,highest_score就存储了列表里的最高分95。

注:原代码最后一行print(score)是错误的,它只会打印列表里最后一个遍历的分数,正确写法应该是print(highest_score),这样才能输出找到的最高分。


内容的提问来源于stack exchange,提问作者Carlos Colón

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:00:08