- This topic is empty.
-
AuthorPosts
-
January 22, 2026 at 11:40 pm #5950
✅ Q&A: Python PhoneBook
add_number()andreturnwith.append()Q1) What does this code do?
class PhoneBook: def __init__(self): self.__persons = {} def add_number(self, name: str, number: str): if not name in self.__persons: self.__persons[name] = [] self.__persons[name].append(number)✅ Answer:
This code creates a phonebook where:self.__personsis a dictionary- Each
namestores a list of phone numbers - If the name does not exist, it creates an empty list
- Then it adds the new number into the list using
.append()
Example result:
{ "Rajeev": ["98765", "12345"] }
Q2) What happens if I add
returnto the last line like this?return self.__persons[name].append(number)✅ Answer:
The number will still be added ✅
BUT the return value will be None ❌Because:
📌
.append()always returnsNone.So this will work:
✅ it will store the numberBut if you do:
result = phonebook.add_number("Rajeev", "99999") print(result)Output will be:
None
Q3) Will adding
returnaffect the functionality of storing the number?✅ Answer:
No, it will not affect storing the number.The number will still be stored properly in the list.
The only change is:
➡️ The method will now return something (which will beNoneif you return.append()).
Q4) Why does
.append()returnNone?✅ Answer:
Because.append()modifies the list in-place.Python list methods like:
.append().sort().reverse()
usually return
Noneto avoid confusion and to show they modify the original list directly.
Q5) What if I want
add_number()to return something meaningful?✅ Answer:
Then use one of these approaches:✅ Option A: Return the updated list
self.__persons[name].append(number) return self.__persons[name]Output example:
["99999"]
✅ Option B: Return True after successful adding
self.__persons[name].append(number) return TrueOutput example:
True
Q6) What if I accidentally write this (wrong approach)?
return number✅ Answer:
This will return the new number string, but it does not return the whole list.It’s not wrong, but usually not useful because your phonebook is supposed to store multiple numbers per person.
Q7) What is the best version of
add_number()for a phonebook?✅ Answer (Recommended):
def add_number(self, name: str, number: str): if name not in self.__persons: self.__persons[name] = [] self.__persons[name].append(number)Simple ✅
Does the job ✅
No unnecessary return ✅
-
AuthorPosts
- You must be logged in to reply to this topic.
