- This topic is empty.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
January 9, 2026 at 12:13 am #5931
π Context: PhoneBook Search Feature
We are building a command-line PhoneBook application in Python.
The application allows users to store names and phone numbers and search for them interactively.The
search()method belongs to the user-interface layer and communicates with aPhoneBookclass that stores data internally.Assumption
The phonebook provides this method:
def get_numbers(self, name): return self.__persons.get(name)- Returns a list of numbers if the name exists
- Returns None if the name is not found
π§© Initial (Correct) Code
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)
β Question
Can I use
breakinstead ofreturnwhen the name is not found?
β Short Answer
No.
breakcannot replacereturnhere.
π§ Explanation
Why
breakFailsbreakcan only be used inside a loop (fororwhile).If you try this:
def search(self): name = input("name: ") numbers = self.__phonebook.get_numbers(name) if numbers is None: print("number unknown") breakPython will raise an error:
SyntaxError: 'break' outside loopThatβs because:
- The
ifstatement is not inside a loop breakdoes not exit functions
π What
breakActually DoesKeyword Purpose breakExits the nearest loop continueSkips to next loop iteration returnExits the entire function
β Why Moving
breakinto the Loop Doesnβt Helpdef search(self): name = input("name: ") numbers = self.__phonebook.get_numbers(name) for number in numbers: if numbers is None: print("number unknown") break print(number)This fails because:
- If
numbersisNone, the loop never starts - Python raises:
TypeError: 'NoneType' object is not iterable
So
breakis never reached.
β Why
returnIs the Correct Choiceif numbers is None: print("number unknown") returnThis:
- Stops the function immediately
- Prevents invalid iteration
- Keeps the code clean and readable
- Follows the guard clause pattern
π Final Takeaway
**Use
breakto exit loops.
-
AuthorPosts
Viewing 1 post (of 1 total)
- You must be logged in to reply to this topic.

