- This topic is empty.
-
AuthorPosts
-
January 31, 2026 at 1:32 am #5985
β Q&A: Phone Book Expansion β Search by Number
β Question
Iβm extending the phone book application to allow searching by number.
In myPhoneBookclass I wrote:if self.__entries[name] = number: return nameBut it doesnβt work. Why is this wrong, and what is the correct way to implement search by number?
β Context: Initial program structure
The phone book stores multiple numbers per person.
Example internal structure:
self.__entries = { "Eric": ["02-123456", "045-4356713"], "Anna": ["040-999999"] }Each name maps to a list of numbers, not a single number.
The template already supports:
- adding entries
- searching by name
Now we are adding:
π searching by number
β Problem in the original line
You wrote:
if self.__entries[name] = number:There are two issues here.
π΄ Issue 1:
=is assignment, not comparisonPython uses:
= assign value == compare valuesInside an
if, you must compare.This causes a syntax error:
if x = 5: # β invalidCorrect:
if x == 5: # β valid
π΄ Issue 2: You compared a list to a string
This:
self.__entries[name]returns a list of numbers.
Example:
["02-123456", "045-4356713"]But you compared it to:
"02-123456"A list will never equal a string:
["02-123456"] == "02-123456" # FalseWe donβt want to compare the whole list.
We want to check if the number exists inside the list.
β Correct solution
We must search each list and check membership:
def search_by_number(self, number: str): for name, numbers in self.__entries.items(): if number in numbers: return name return NoneKey idea:
π
"number in numbers"checks if the number exists in that person’s list.
π§ How the loop works
For each person:
Eric β ["02-123456", "045-4356713"] Anna β ["040-999999"]We ask:
Does this number appear in their list?
If yes β return the name.
If no match β return
None.
β Alternative version (same logic)
You could also write:
def search_by_number(self, number: str): for name in self.__entries: if number in self.__entries[name]: return name return NoneThis is equivalent β just different syntax.
β Expected behavior
command: 3 number: 02-123456 Eric command: 3 number: 0100100 unknown number
-
AuthorPosts
- You must be logged in to reply to this topic.

