Generate a Python list from input

Generate a Python list from input … here is a solution to the problem.

Generate a Python list from input

I recently started a Python class with PluralSight, and one of the early modules on list creation and input left me a bit confused. I wrote the same code as the one introduced by the instructor, but it didn’t work the way I thought it would.

We were asked to take a code that asked for 2 inputs, a name and a student number, and add to

it to create a program that asked for these 2 inputs, and then asked the user if they wanted to add another name and number. If they do, it asks for another name, number, and if the user wants to add more. If the user refuses, it should print out a list of names (but not numbers).

I

came up with a code to do this, but when I print out the list, it only prints out the recently entered name. I don’t know how to print a list of multiple names, any suggestions? Thanks!

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()

Solution

Look at the third line of get_students_titlecase. You should append to the array, not set it to a value.

students_titlecase.append(student["name"].title())

Related Problems and Solutions