[python] Using a Loop to add objects to a list(python)

I'm trying to use a while loop to add objects to a list.

Here's basically what I want to do:

class x:
     pass

choice = raw_input(pick what you want to do)

while(choice!=0):
    if(choice==1):
       Enter in info for the class:
       append object to list (A)
    if(choice==2):
       print out length of list(A)
    if(choice==0):
       break
    ((((other options))))

I can get the object added to the list, but I am stuck at how to add multiple objects to the list in the loop.

Here is the code I have so far:

print "Welcome to the Student Management Program"

class Student:  
    def __init__ (self, name, age, gender, favclass):  
         self.name   = name  
         self.age    = age  
         self.gender = gender  
         self.fac = favclass  

choice = int(raw_input("Make a Choice: " ))

while (choice !=0):
    if (choice==1):  
        print("STUDENT")  
        namer = raw_input("Enter Name: ")  
        ager = raw_input("Enter Age: ")  
        sexer = raw_input("Enter Sex: ")  
        faver = raw_input("Enter Fav: ")      

    elif(choice==2):
        print "TESTING LINE"
    elif(choice==3):
        print(len(a))

    guess=int(raw_input("Make a Choice: "))

    s = Student(namer, ager, sexer, faver)
    a =[];
    a.append(s)

raw_input("Press enter to exit")

Any help would be greatly appreciated!

This question is related to python list object loops while-loop

The answer is


The problem appears to be that you are reinitializing the list to an empty list in each iteration:

while choice != 0:
    ...
    a = []
    a.append(s)

Try moving the initialization above the loop so that it is executed only once.

a = []
while choice != 0:
    ...
    a.append(s)

Auto-incrementing the index in a loop:

myArr[(len(myArr)+1)]={"key":"val"}

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to while-loop

While, Do While, For loops in Assembly Language (emu8086) MySQL Insert with While Loop Python loop to run for certain amount of seconds How to break a while loop from an if condition inside the while loop? How to find sum of several integers input by user using do/while, While statement or For statement Python: How to keep repeating a program until a specific input is obtained? Creating multiple objects with different names in a loop to store in an array list ORA-06502: PL/SQL: numeric or value error: character string buffer too small How to break out of a loop in Bash? for or while loop to do something n times