简体   繁体   中英

Append Values from input to a sublist in Python

I am trying to append values from an input to sublists in a list. Each number of Student and name should be in a sublist. ex:

[[123,John],[124,Andrew]]

Where the outside list would be the number of students, and the sublists , the info of the students..

Here is what my code looks like:

listStudents = [[] for _ in range(3)]
infoStudent = [[]]

while True:
    choice = int(input("1- Register Student 0- Exit"))
    cont = 0
    if choice == 1:
            snumber = str(input("Student number: "))
            infoStudent[cont].append(str(snumber))
            name = str(input("Name : "))
            infoStudent[cont].append(str(name))
            cont+=1
            listStudents.append(infoStudent)
    if choice == 0:
        print("END")
        break


print(listStudents)

print(infoStudent)

If I put on the first loop, snumber = 123 , name = john , and snumber = 124 , name = andrew on the second time it will show me : [[123,john,124,andrew]] instead of [[123,john], [124,andrew]] .

Your code can be greatly simplified:

  1. You don't need to pre-allocate the lists and sublists. Just have one list, and append the sublists as you receive inputs.
  2. You don't need to cast user input from input to strings, as they are strings already.

Here's the modified code:

listStudents = []

while True:
    choice = int(input('1- Register Student 0- Exit'))
    if choice == 1:
        snumber = input('Student number: ')
        name = input('Name : ')
        listStudents.append([snumber, name])
    if choice == 0:
        print('END')
        break

print(listStudents)

Your code can be more pythonic and can make use of some basic error handling as well. Create the inner list inside the while loop and simply append to the outer student list. This should work.

students = []
while True:
    try:
        choice = int(input("1- Register Student 0- Exit"))
    except ValueError:
        print("Invalid Option Entered")
        continue

    if choice not in (1, 9):
        print("Invalid Option Entered")
        continue

    if choice == 1:
        snumber = str(input("Student number: "))
        name = str(input("Name : "))
        students.append([snumber, name])
    elif choice == 0:
        print("END")
        break

print(students)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM