Beginner programmer here. I created a class that makes a student object, and I need a way for each object the user creates to not overwrite the previous objects and make them all the same. That may be a poor explanation so I will just post the code and the output.
class Student:
"""This class holds student records """
student_id = 000
def __init__(self,firstname='blank',lastname='blank',age=0,sex='NA',major='undeclared',graduation=0):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.sex = sex
self.major = major
self.graduation= graduation
Student.student_id +=1
self.student_id = Student.student_id
students=[]
while True:
new_student=Student(input('Enter student first name: '),input('Enter student last name: '),input('Enter student age: '),input("Enter student sex: "),input("Enter student's major: "),input("Enter student's expected graduation date: "))
students.append(new_student)
add_another=input("Would you like to add another student? Enter 'Y' for yes or any other key to quit and print your entries: ")
if add_another == 'Y':
continue
else:
for i in students:
print(new_student.firstname)
print(new_student.student_id)
break
my output looks like this currently:
Enter student first name: Thomas
Enter student last name: Hutton
Enter student age: poop
Enter student sex: p
Enter student's major: p
Enter student's expected graduation date: p
Would you like to add another student? Enter 'Y' for yes or any other key to quit and print your entries: Y
Enter student first name: Timmy
Enter student last name: p
Enter student age: p
Enter student sex: p
Enter student's major: p
Enter student's expected graduation date: p
Would you like to add another student? Enter 'Y' for yes or any other key to quit and print your entries: n
Timmy
2
Timmy
2
as you can see the only object that now populates the students list is now the same object for both entries, I need them to be the entries that were provided by the user. Thanks for any help.
>Solution :
When you are looping over students you are not referencing the right variable. new_student should should be i
for i in students:
print(i.student_id)
print(i.firstname)
But I would recommend changing the i variable to student, so it reads like
for student in students:
print(student.firstname)
i is typically used to represent an integer index in a list.