We are going to build a contact book bit by bit, the way a programmer would: first the minimum that works and then we add pieces, checking each one. The complete project with a different output format is in Contact book.
Step 1: the data
We will search by name, so we use a dictionary with the name as key and the phone as value.
book = {}
book["Ana"] = "600111222"
book["Luis"] = "600333444"
print(book) # {'Ana': '600111222', 'Luis': '600333444'}
Step 2: one function per operation
Each function does one thing and returns a message instead of printing it; this makes it easy to test.
def add_contact(book, name, phone):
message = "Updated" if name in book else "Added"
book[name] = phone
return f"{message}: {name}"
def find_contact(book, name):
if name in book:
return f"{name}: {book[name]}"
return f"Not found: {name}"
def delete_contact(book, name):
if name in book:
del book[name]
return f"Deleted: {name}"
return f"Not found: {name}"
Step 3: test before going on
With assert we check the normal cases and the edge cases. If something fails, you know right away, not at the end.
data = {}
assert add_contact(data, "Ana", "111") == "Added: Ana"
assert add_contact(data, "Ana", "222") == "Updated: Ana"
assert find_contact(data, "Ana") == "Ana: 222"
assert find_contact(data, "Eva") == "Not found: Eva"
assert delete_contact(data, "Ana") == "Deleted: Ana"
assert delete_contact(data, "Ana") == "Not found: Ana"
print("All correct") # All correct
Step 4: interpret a command
A function that receives a line of text, decides which operation to run and returns the message. It is the piece that links the input text with the functions.
def process(book, line):
parts = line.split()
command = parts[0]
if command == "add":
return add_contact(book, parts[1], parts[2])
if command == "find":
return find_contact(book, parts[1])
if command == "delete":
return delete_contact(book, parts[1])
return f"Unknown command: {command}"
data = {}
print(process(data, "add Eva 700")) # Added: Eva
print(process(data, "find Eva")) # Eva: 700
print(process(data, "jump")) # Unknown command: jump
Step 5: the main program
Now we only need to read the commands and show the result. Notice how short it is thanks to the previous pieces.
def main():
book = {}
n = int(input())
for _ in range(n):
print(process(book, input()))
print(f"Contacts: {len(book)}")
main()
Step 6: improve
A program that works is the starting point, not the end. Some possible improvements:
- Validate the input:
add Anawithout a phone causes anIndexError. Catch it withtry/exceptor checklen(parts). - Save the book to a JSON file with
json.dumpand load it on startup. - Turn the book into a
Bookclass when it has more operations, as Inventory control does. - Add the tests as a
unittestfile instead of looseassertstatements.
The underlying lesson is the work order: data, small functions, tests, main program and, finally, improvements.