最近我开始通过PluralSight学习Python,早期的一个列表创建和输入模块让我有些困惑。我编写了与讲师演示代码相同的代码,但它没有按照我想象的那样运行。
我们被要求编写一个程序,要求用户输入2个参数:姓名和学生ID号码。然后添加代码,使程序能够继续询问用户是否要添加另外一个姓名和号码。如果用户想要添加,程序会要求输入另外一个姓名、号码并询问用户是否要添加更多。如果用户回答不,程序应该打印出姓名列表(但不包括号码)。
我编写了一个这样的代码,但是当我打印输出列表时,它只打印出最近输入的姓名。我无法弄清楚如何打印出多个姓名的列表,请问有什么建议吗?谢谢!
students = []
def get_students_titlecase():
students_titlecase = []
for student in students:
students_titlecase = student["name"].title()
return students_titlecase
def print_students_titlecase():
students_titlecase = get_students_titlecase()
print(students_titlecase)
def add_student(name, student_id=332):
student = {"name": name, "student_id": student_id}
students.append(student)
student_list = get_students_titlecase()
student_name = input("Enter Student name: ")
student_id = input("Enter Student id: ")
add_student(student_name, student_id)
add_more = input("Add another student? [y/n]: ")
while add_more == "y":
student_name = input("Enter Student name: ")
student_id = input("Enter Student id: ")
add_student(student_name, student_id)
add_more = input("Add another student? [y/n]: ")
if add_more == "n":
print_students_titlecase()