如何通过循环批量创建13个结构相同的学生信息列表?
当然可以用循环实现,无需手动重复编写
完全没必要手动写13遍相同的输入逻辑,通过循环搭配函数封装,既能完成需求,还能让代码更简洁、易维护。
实现思路
- 把单个学生的输入验证逻辑封装成独立函数,每次调用就能获取一个学生的完整数据;
- 循环13次调用这个函数,把每个学生的数据统一存到一个大列表里(比如
students),后续可通过索引访问对应学生的数据(比如students[0]对应第一个学生,students[12]对应第十三个学生)。
示例代码
def get_student_data(): student = [] name = input('Input the name of the student: ') student.append(name) # 处理8位密码输入 password = input('Input the 8 digit password: ') while len(password) != 8: print('Password is not 8 digits long!') password = input('Input the 8 digit password: ') student.append(password) # 处理第一个成绩输入 grade1 = float(input('Input the first grade between 0 and 10: ')) while grade1 < 0 or grade1 > 10: print('Invalid grade!') grade1 = float(input('Input the first grade between 0 and 10: ')) # 处理第二个成绩输入 grade2 = float(input('Input the second grade between 0 and 10: ')) while grade2 < 0 or grade2 > 10: print('Invalid grade!') grade2 = float(input('Input the second grade between 0 and 10: ')) average = (grade1 + grade2) / 2 student.append(average) return student # 循环13次收集所有学生数据 students = [] for _ in range(13): print(f"\n--- 输入第{len(students)+1}个学生信息 ---") student_data = get_student_data() students.append(student_data) # 验证结果:打印所有学生信息 print("\n所有学生信息:") for idx, student in enumerate(students, 1): print(f"学生{idx}: 姓名={student[0]}, 密码={student[1]}, 平均分={student[2]:.2f}")
额外优化建议
如果想让数据结构更清晰,也可以用字典存储单个学生信息(比如{'name': name, 'password': password, 'average': average}),后续访问数据时直接用键名(student['name'])比索引更直观,不容易搞混顺序。
内容的提问来源于stack exchange,提问作者Ian Lohan
相关产品推荐
相关产品推荐

