views:

150

answers:

1

Hey guys so im trying to use a while loop to add objects to a list.

Heres bascially what i want to do: (ill paste actually go after)

class x:
     blah
     blah

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

as im doing this i can get the object to get added to the list, but i am stuck as to how to add multiple objects to the list in the loop.

Here is my actual 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!

+3  A: 

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)
Mark Byers
so outside the loop i should havea=[]and then inside the loop i should havea.append(s)?
Will
@Will: That is probably a good start, although there are some other issues with your code. If you enter a number other than 0 or 1 you will add the same student to the list again. Is this really what you want?
Mark Byers
haha and um no....i want the ability to go through the loop and add a different student each time i choose 1... so i would go through once, add a student, choose 1 again and add a different student...etc...etcso each time i go through i can add a diff student
Will
but at the end of the loop iw ould have the user enter in new information for the student class so wouldnt that take the place of the old info?
Will
@Will: I would move the code that appends to the list to be inside the `if choice == 1:` block. It should not run in the other cases.
Mark Byers
so inside.. if(choice==1): append it to the list here?
Will
@Will: Yes, immediately after the raw_inputs.
Mark Byers
ok thanks...im going to try it out again and ill get back to this question if i have...any other questions!you rock
Will