Python循环输入学生信息并格式化输出
students = []
for _ in range(3):
name = input('请输入学生姓名:')
number = input('请输入学生学号:')
students.append((name, number))
for student in students:
print(f'{student[0]}同学的学号是{student[1]}。')
这段代码演示了如何使用Python循环语句和列表来存储和输出学生信息。
代码解释:
students = []: 创建一个空列表students用于存储学生信息。for _ in range(3):: 使用for循环语句循环三次,获取三名学生的信息。name = input('请输入学生姓名:'): 提示用户输入学生姓名并存储在变量name中。number = input('请输入学生学号:'): 提示用户输入学生学号并存储在变量number中。students.append((name, number)): 将学生姓名和学号作为一个元组添加到students列表中。for student in students:: 遍历students列表中的每个学生信息。print(f'{student[0]}同学的学号是{student[1]}。'): 使用 f-string 格式化输出每个学生的姓名和学号,其中student[0]表示姓名,student[1]表示学号。
运行这段代码后,程序会依次提示输入三名学生的姓名和学号,并将输入的信息存储在列表中。最后,程序会遍历列表并按指定格式输出每个学生的姓名和学号信息。
原文地址: http://www.cveoy.top/t/topic/rny 著作权归作者所有。请勿转载和采集!