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

Python程序问题:如何实现成绩单行输入而非逐个录入?

实现单行输入成绩的修改方案

把原来逐个输入成绩的逻辑替换成单行输入处理即可,修改后的代码如下:

num_students = int(input("Enter the number of students: "))
# 单行输入所有成绩,用空格分隔
scores_input = input("Enter all scores separated by spaces: ")
# 将输入字符串分割并转换为整数列表
scores = list(map(int, scores_input.split()))

# 可选:验证输入的成绩数量是否与学生数一致
if len(scores) != num_students:
    print(f"Error: You entered {len(scores)} scores, but there are {num_students} students.")
else:
    best_score = max(scores)
    for i in range(num_students):
        if scores[i] >= best_score - 10:
            grade = "A"
        elif scores[i] >= best_score - 20:
            grade = "B"
        elif scores[i] >= best_score - 30:
            grade = "C"
        elif scores[i] >= best_score - 40:
            grade = "D"
        else:
            grade = "F"
        print(f"Student {i} score is {scores[i]} and grade is {grade}")

关键修改说明

  • 用input()一次性获取单行输入的所有成绩,替代原来的循环逐个输入
  • 通过split()方法将输入的字符串按空格分割成多个子字符串,再用map(int, ...)转换为整数类型,最后转为列表存入scores
  • 增加了成绩数量验证,防止输入的成绩个数和学生数不匹配导致后续逻辑出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:55:22