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
相关产品推荐
相关产品推荐

