livepython.net

245. Python Program to Make a Contact Book with Commands

MediumPhase 2 · Practice

There are a few steps here, and you know every tool: a while loop, split() and a dictionary.

Overview

A contact book links each name to a phone number. A dictionary works the same way: you look up a value by its key.

Problem Statement

Noah keeps friends' phone numbers in a small program. The contact book starts empty. Read one command per line until a line says end. The commands are:

  • add <name> <phone>: save the name with its phone number and print Saved <name>. If the name is already saved, print <name> is already saved and keep the old number.
  • find <name>: print <name>: <phone>. If the name is not saved, print <name> not found.
  • delete <name>: remove the name and its number, and print Deleted <name>. If the name is not saved, print <name> not found.

For any other command, print Unknown command. After end, print Contacts: <count>: how many names are saved at the end.

Names must match exactly: Ana and ana are different names. Keep the phone number as text, so a number like 0712345678 keeps its first zero.

Examples

Example 1. Input:

add Sara 0712345678
add Kenji 0698765432
find Kenji
delete Sara
find Sara
end

gives:

Saved Sara
Saved Kenji
Kenji: 0698765432
Deleted Sara
Sara not found
Contacts: 1

Why: Sara is deleted, so the second search cannot find Sara. Only Kenji is left, so the count is 1.

Example 2. Input:

add Bilal 5550101
add Bilal 5550999
find Bilal
delete Omar
call Bilal
end

gives:

Saved Bilal
Bilal is already saved
Bilal: 5550101
Omar not found
Unknown command
Contacts: 1

Why: the second add for Bilal is refused, so Bilal's first number stays. Omar was never saved, and call is not a command.

Input

One command per line, in the formats above, with one space between the parts. Names and phone numbers are one word each. The last line is always end. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line for each command, then the Contacts: line. The tests try 7 different inputs, also an empty book, names with different capital letters and a one-word unknown command.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 13 · Dictionaries
solution.py
# write your code here

EXPECTED OUTPUT

1Saved Sara
2Saved Kenji
3Kenji: 0698765432
4Deleted Sara
5Sara not found
6Contacts: 1

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.