- This topic is empty.
-
AuthorPosts
-
January 19, 2026 at 10:28 pm #5945
✅ Context
A learner is building a simple PhoneBook class in Python.
The goal is:- Store contact names
- Allow multiple phone numbers for the same name
- Retrieve stored numbers later
Here is the initial code:
class PhoneBook: def __init__(self): self.__persons = {} def add_number(self, name: str, number: str): if not name in self.__persons: # add a new dictionary entry with an empty list for the numbers self.__persons[name] = [] self.__persons[name].append(number) def get_numbers(self, name: str): if not name in self.__persons: return None return self.__persons[name]
❓ Q1) What is
self.__personsstoring?✅ Answer:
self.__personsis a dictionary.- Keys = contact names (
str) - Values = a list of phone numbers (
list[str])
Example structure:
{ "Raj": ["999", "888"], "Alex": ["123"] }
❓ Q2) Why are we using an empty list
[]when adding a new name?✅ Answer:
Because the code wants to store multiple numbers per person.So when a name is seen for the first time:
self.__persons[name] = []Then every new number gets added using:
self.__persons[name].append(number)
❓ Q3) What does this line do?
return self.__persons[name]✅ Answer:
It sends back the list of numbers stored for that name.So if we do:
pb.get_numbers("Raj")It could return:
["999", "888"]
❓ Q4) What if I write this instead?
number = self.__persons[name]✅ Answer:
That is totally fine.It stores the contact’s phone numbers inside a variable.
Example:
numbers = self.__persons[name] return numbers
❓ Q5) What happens if I do NOT return anything at the end?
Example:
def get_numbers(self, name: str): if name not in self.__persons: return None numbers = self.__persons[name] # no return here✅ Answer:
Then Python will automatically return None.Because in Python:
If a function ends without
return, it returnsNoneby default.
❓ Q6) But I stored it in a variable… why doesn’t it work without return?
✅ Answer:
Because variables inside a function exist only inside that function.So this line:
numbers = self.__persons[name]only stores it temporarily inside the function.
If you want the caller to receive that value, you must return it.
❓ Q7) What will this print?
pb = PhoneBook() pb.add_number("Raj", "999") print(pb.get_numbers("Raj"))✅ Answer:
If the function has this line:return self.__persons[name]Output will be:
['999']But if you remove the return statement, output will be:
None
❓ Q8) Why does
get_numbers()returnNonefor a missing name?✅ Answer:
Because this part runs:if not name in self.__persons: return NoneSo if a name is not found, it clearly signals:
✅ “This person doesn’t exist in the phonebook.”
✅ Quick Summary for Beginners
✅
self.__persons[name]is a list of numbers
✅ To send that list back, you needreturn
✅ If you don’t return anything, Python returnsNoneautomatically
✅ Storing in a variable is useful, but it does not automatically “send it back”
-
AuthorPosts
- You must be logged in to reply to this topic.

