I have an arbitrary number of objects created from this class:
class Person:
def __init__(self, name, email):
self.name = name
self.email = email
I have a list of these objects:
myList = []
JohnDoe = Person("John Doe", "jdoe@email.com")
BobbyMcfry = Person("Bobby Mcfry", "bmcfry@email.com")
WardWilkens = Person("Ward Wilkens", "wwilkens@email.com")
myList.append(JohnDoe)
myList.append(BobbyMcfry)
myList.append(WardWilkens)
I am wanting to check if someone exists, and if so, return their attributes – if not, say so:
x = input("Who to check for? ")
for i in myList:
if i.name == x:
print("Name: {0}\nEmail: {1}".format(i.name, i.email))
else:
print("{0} is not on the manifest.".format(x))
This kind of works, but returns one or the other for each Person in myList – I only want one return…
I realize I need to do some sort of
if val in myList:....
But I’m having trouble how to word what “val” should be without iterating through each object
Using the loop is fine, you just need to handle the case where none of the names matched, you can do this easily using
breakandelse:Depending on what you use the list for, you might be better of using a dictionary to link names to
Personobjects: