- This topic is empty.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
January 22, 2026 at 1:33 am #5947
✅ Q & A (with Initial Code + Context)
Context
You are building a PhoneBook program where:
- Each person can have multiple phone numbers
- Phone numbers are stored as a list
- Data is loaded from a file and inserted into the phonebook
✅ Initial Code
PhoneBook class
class PhoneBook: def __init__(self): self.__persons = {} def add_number(self, name: str, number: str): if name not in self.__persons: self.__persons[name] = [] self.__persons[name].append(number) def get_numbers(self, name: str): if name not in self.__persons: return None return self.__persons[name]
PhoneBookApplication class (loading from file)
class PhoneBookApplication: def __init__(self): self.__phonebook = PhoneBook() self.__filehandler = FileHandler("phonebook.txt") # add the names and numbers from the file to the phone book for name, numbers in self.__filehandler.load_file().items(): for number in numbers: self.__phonebook.add_number(name, number)
✅ Q: Why does
get_numbers()return the full list directly without a loop, but in other places we need a loop?✅ A:
Because
get_numbers()is only returning data, not processing it.return self.__persons[name]That is already a list, so returning it directly is correct.
✅ Q: In
search(), why do we loop through numbers instead of printing the list directly?for number in numbers: print(number)✅ A:
Loop is not mandatory, it is done for clean display.
If you print directly:
print(numbers)Output would look like:
['111', '222', '333']But the loop gives a cleaner output:
111 222 333
✅ Q: In
PhoneBookApplication.__init__, why is the inner loop mandatory?for name, numbers in self.__filehandler.load_file().items(): for number in numbers: self.__phonebook.add_number(name, number)✅ A:
Because
add_number()accepts only ONE number at a time, like:add_number(name, "111")But from the file,
numbersis a list:numbers = ["111", "222", "333"]So you must loop and add them one-by-one.
✅ Q: What happens if we remove the inner loop and do this instead?
self.__phonebook.add_number(name, numbers)✅ A:
Then the phonebook will store a list inside a list, like this:
"Alice": [["111", "222", "333"]]That is incorrect because later your search will give:
[['111', '222', '333']]So ✅ inner loop is required to avoid nested lists.
✅ Final Summary
get_numbers()returns the listsearch()loops for nice printingload_file()+add_number()requires looping because you must add each number separately
-
AuthorPosts
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.
