When I try to check if the user's input is the same as an object attribute in a list it checks the objects that were stated within the list instead of objects that were appended to the list.
This was a problem that was really hard to explain and I tried my best to. Please let me know if it doesn't make sense or if you want more information.
I am making a contact list for context. I made a contact class with a name, number, and address attributes. I am trying to see if a number that the user inputs is the same an object's number attribute in a list. However when I was debugging and putting contacts in the list when it is stated, it works. When I append new contacts and try to see if the code knows if the user's input is the same as the appended contacts it doesn't work.
Here is my code:
class Contact:
def __init__(self, name, number, address):
self.name = name
self.number = number
self.address = address
def __str__(self):
return f"{self.name}, ({self.number}), {self.address}"
contact_list = []
def add_contact():
global contact_list
valid_name = False
valid_number = False
while not valid_name:
contact_name = input("Who would you like to add as your contact?: ")
name_taken = False
for contact in contact_list:
if contact.name == contact_name:
print("Name is taken in contacts!")
name_taken = True
break
if not name_taken:
valid_name = True
while not valid_number:
contact_number = input("What is their number?: ")
if len(contact_number) == 10 and contact_number.isnumeric():
number_taken = False
for contact in contact_list:
if contact.number == int(contact_number):
print("Number is taken in contacts!")
number_taken = True
break
if not number_taken:
valid_number = True
else:
valid_number = False
else:
print("Invalid number!")
contact_address = input("What is their house address?: ")
new_contact = Contact(contact_name, contact_number, contact_address)
contact_list.append(new_contact)
print("Contact list:")
for contact in contact_list:
print("- " contact.__str__())
add_contact()
add_contact()
CodePudding user response:
Contact number is stored as a string in contact_list
, so it never matches the int
you compare it to.