Reputation: 3
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]]
.
Upvotes: 0
Views: 765
Reputation: 1874
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)
Upvotes: 0
Reputation: 8610
Your code can be greatly simplified:
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)
Upvotes: 3