- This topic is empty.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
January 16, 2026 at 4:41 am #5939
✅ Context
You are building a PhoneBook Application in Python.
- The app stores phone numbers inside a
PhoneBookclass - It reads saved contacts from a text file using a
FileHandlerclass - When the app starts, it should load all saved names and numbers from the file and insert them into the phonebook.
✅ Initial Code (Correct Version)
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) # the rest of the program...
❓ Question
Why is this version incorrect?
for name, numbers in self.__filehandler.load_file().items(): self.__phonebook.add_number(name, numbers)
✅ Answer (Easy Explanation)
Because
numbersis not one phone number…
numbersis actually a list of multiple phone numbers.So if your file contains:
{ "Rajeev": ["9991112222", "8887776666"], "Amit": ["1234567890"] }Then:
name = "Rajeev"numbers = ["9991112222", "8887776666"]✅ (a list!)
But your method expects a single number, like:
add_number("Rajeev", "9991112222")Not:
add_number("Rajeev", ["9991112222", "8887776666"])
✅ What Happens If You Use the Incorrect Code?
Inside your
PhoneBookclass, you likely have:self.__persons[name].append(number)So instead of storing:
✅ Correct output:
"Rajeev": ["9991112222", "8887776666"]You accidentally store:
❌ Wrong output:
"Rajeev": [["9991112222", "8887776666"]]That means Python stores the entire list as one single item.
✅ Correct Logic (Final Fix)
You must loop through the list of numbers:
for name, numbers in self.__filehandler.load_file().items(): for number in numbers: self.__phonebook.add_number(name, number)✅ This inserts each phone number one-by-one properly.
ߎ Quick Summary for Beginners
✅
.items()gives you: name + list of numbers
✅add_number()needs: name + single number
✅ So you must use a nested loop.
- The app stores phone numbers inside a
-
AuthorPosts
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.

