- This topic is empty.
-
AuthorPosts
-
January 8, 2026 at 11:26 am #5930
π Context: PhoneBook Search Function
We are building a command-line PhoneBook application in Python.
Thesearch()method allows a user to enter a name and retrieve the stored phone numbers for that person.The phonebook logic is handled by a separate
PhoneBookclass, and the user interface is managed byPhoneBookApplication.Relevant Assumption
The method below exists in
PhoneBook:def get_numbers(self, name): return self.__persons.get(name)- Returns a list of phone numbers if the name exists
- Returns None if the name is not found
β Question
Is it okay if my
search()function only contains this code?def search(self): name = input("name: ") numbers = self.__phonebook.get_numbers(name)
β Short Answer
Yes, the code will run β but it is NOT sufficient for a search feature.
π§ Explanation
This shortened version:
def search(self): name = input("name: ") numbers = self.__phonebook.get_numbers(name)What it does
- βοΈ Accepts user input
- βοΈ Fetches data from the phonebook
What it does NOT do
- β Does not display the result
- β Does not handle missing names
- β Does not inform the user if the number is unknown
- β Discards the fetched data silently
So while the function executes without errors, it provides no user feedback, making it functionally incomplete.
β Correct and Complete Version
def search(self): name = input("name: ") numbers = self.__phonebook.get_numbers(name) if numbers is None: print("number unknown") return for number in numbers: print(number)
π Why the
NoneCheck Is EssentialIf the name does not exist,
get_numbers()returnsNone.Trying to loop over
Nonelike this:for number in numbers: print(number)would cause a runtime error:
TypeError: 'NoneType' object is not iterableThe check:
if numbers is None:prevents this crash and allows the program to fail gracefully.
π§© Why
returnIs Used Herereturn- Immediately exits the
search()function - Prevents further execution
- Keeps the control flow clean
- Avoids unnecessary
elseblocks
This is a classic guard clause pattern.
π Teaching Takeaway
A search function must either show results or explain why it canβt.
Fetching data without displaying or validating it makes the function technically valid but logically incomplete.
-
AuthorPosts
- You must be logged in to reply to this topic.

