2024-10-02 02:32:47 发布
网友
我试图将输入中的值附加到列表中的子列表中。 每个学生的人数和姓名都应该在一个子列表中。 例如:
[[123,John],[124,Andrew]]
外部列表是学生人数,子列表是学生的信息。。在
下面是我的代码:
如果我打开第一个循环,snumber = 123,name = john,和snumber = 124,name = andrew在第二次时它将显示给我:[[123,john,124,andrew]],而不是{}。在
snumber = 123
name = john
snumber = 124
name = andrew
[[123,john,124,andrew]]
您的代码可以大大简化:
input
修改后的代码如下:
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)
您的代码可以更python,也可以使用一些基本的错误处理。在while循环中创建内部列表,并简单地附加到外部学生列表中。这应该行得通。在
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)
您的代码可以大大简化:
input
转换为字符串,因为它们已经是字符串了。在修改后的代码如下:
您的代码可以更python,也可以使用一些基本的错误处理。在while循环中创建内部列表,并简单地附加到外部学生列表中。这应该行得通。在
相关问题 更多 >
编程相关推荐