students = []
for _ in range(3):
    name = input('请输入学生姓名:')
    number = input('请输入学生学号:')
    students.append((name, number))

for student in students:
    print(f'{student[0]}同学的学号是{student[1]}。')

这段代码演示了如何使用Python循环语句和列表来存储和输出学生信息。

代码解释:

  1. students = []: 创建一个空列表 students 用于存储学生信息。
  2. for _ in range(3):: 使用 for 循环语句循环三次,获取三名学生的信息。
  3. name = input('请输入学生姓名:'): 提示用户输入学生姓名并存储在变量 name 中。
  4. number = input('请输入学生学号:'): 提示用户输入学生学号并存储在变量 number 中。
  5. students.append((name, number)): 将学生姓名和学号作为一个元组添加到 students 列表中。
  6. for student in students:: 遍历 students 列表中的每个学生信息。
  7. print(f'{student[0]}同学的学号是{student[1]}。'): 使用 f-string 格式化输出每个学生的姓名和学号,其中 student[0] 表示姓名,student[1] 表示学号。

运行这段代码后,程序会依次提示输入三名学生的姓名和学号,并将输入的信息存储在列表中。最后,程序会遍历列表并按指定格式输出每个学生的姓名和学号信息。

Python循环输入学生信息并格式化输出

原文地址: http://www.cveoy.top/t/topic/rny 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录