题目:

编写input()和output()函数输入、输出5个学生的数据记录。

简介:

在本篇博客中,我们将解决一个输入输出问题:编写input()和output()函数来输入和输出5个学生的数据记录。我们将介绍如何使用这两个函数来进行数据的输入和输出,并提供一个完整的代码示例。

问题分析:

我们需要编写两个函数:input()函数用于输入5个学生的数据记录,output()函数用于输出这些记录。

解决方案:

为了解决这个问题,我们可以使用循环和字符串格式化来实现输入和输出操作。

下面是解题的代码示例:

登录后复制

def input_students():
    students = []
    for i in range(1, 6):
        name = input("请输入第{}个学生的姓名:".format(i))
        age = input("请输入第{}个学生的年龄:".format(i))
        score = input("请输入第{}个学生的成绩:".format(i))
        student = {"姓名": name, "年龄": age, "成绩": score}
        students.append(student)
    return students

def output_students(students):
    print("学生数据记录:")
    for i, student in enumerate(students):
        print("第{}个学生:".format(i+1))
        print("姓名:{}".format(student["姓名"]))
        print("年龄:{}".format(student["年龄"]))
        print("成绩:{}".format(student["成绩"]))
        print()

# 输入学生数据
students_data = input_students()

# 输出学生数据
output_students(students_data)
  • .

运行结果如下:

登录后复制

请输入第1个学生的姓名:Alice
请输入第1个学生的年龄:20
请输入第1个学生的成绩:90
请输入第2个学生的姓名:Bob
请输入第2个学生的年龄:19
请输入第2个学生的成绩:85
请输入第3个学生的姓名:Charlie
请输入第3个学生的年龄:21
请输入第3个学生的成绩:95
请输入第4个学生的姓名:David
请输入第4个学生的年龄:18
请输入第4个学生的成绩:92
请输入第5个学生的姓名:Emily
请输入第5个学生的年龄:20
请输入第5个学生的成绩:88

学生数据记录:
第1个学生:
姓名:Alice
年龄:20
成绩:90

第2个学生:
姓名:Bob
年龄:19
成绩:85

第3个学生:
姓名:Charlie
年龄:21
成绩:95

第4个学生:
姓名:David
年龄:18
成绩:92

第5个学生:
姓名:Emily
年龄:20
成绩:88

代码解析:

  1. 我们定义了两个函数:input_students()和output_students(),用于输入和输出学生的数据记录。
  2. 在input_students()函数中,我们使用循环来输入每个学生的姓名、年龄和成绩,并将其存储在一个字典中,然后将字典添加到一个列表中。
  3. 在output_students()函数中,我们使用循环和字符串格式化来逐个输出学生的数据记录。
  4. 在主程序中,我们首先调用input_students()函数来输入学生数据,然后将返回的数据作为参数传递给output_students()函数来输出学生数据。

结论:

通过运行上述代码,我们可以输入和输出5个学生的数据记录。这个问题通过编写input()和output()函数,利用循环和字符串格式化实现了学生数据的输入和输出。这个简单的代码示例展示了如何使用Python解决输入输出问题,并可帮助读者更好地理解函数、循环和字符串格式化的应用。