Please help me see what I am missing below. I first created three objects of my class and added them to a collection list. Before creating any additional objects, I want to check to make sure that that person does not already exist in the list. If the person already exists, the person shouldn't be created again. I was hoping to achieve this check by doing if prompt_fname == person.fname and prompt_lname == person.lname:
. Apparently, I'm not doing it correctly because the program still ran through and created the same person who already exists in the list. And it created this person two times. How can I modify to catch this so that a person already existing in the list is not created again. Also any new person should not be created again and again in each iteration of the loop. I'm new to programming so please don't leave out much detail in your answer. Thanks a lot.
class Person(object):
personslist = []
'''Creates a person object'''
def __init__(self, firstname, lastname):
self.lname = lastname.title()
self.fname = firstname.title()
Person.personslist.append(self)
def __str__(self):
return "{0} {1}".format(self.fname, self.lname)
def __repr__(self):
return "{0} {1}".format(self.fname, self.lname)
Person("Adamu", "Emeka")
Person("Femi", "Ojukwu")
Person("Wole", "Jonathan")
prompt_fname = "Adamu"
prompt_lname = "Emeka"
print(Person.personslist)
for person in Person.personslist:
if prompt_fname == person.fname and prompt_lname == person.lname:
pass
else:
Person(prompt_fname, prompt_lname)
print(Person.personslist)
Yields
[Adamu Emeka, Femi Ojukwu, Wole Jonathan]
[Adamu Emeka, Femi Ojukwu, Wole Jonathan, Adamu Emeka, Adamu Emeka]
Using Python 3.4.1