Skip to content

Commit 6e44c79

Browse files
authored
Create contact-book-code.md
1 parent bc240f0 commit 6e44c79

1 file changed

Lines changed: 142 additions & 0 deletions

File tree

contact-book/contact-book-code.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
2+
Contact Book Application
3+
------------------------------------
4+
A simple command-line contact management app.
5+
It allows the user to:
6+
1. Add new contacts
7+
2. View all contacts
8+
3. Search for a contact
9+
4. Delete a contact
10+
11+
All contacts are saved in a local file ('contacts.txt') for persistence.
12+
13+
Concepts used:
14+
- File handling
15+
- Lists and dictionaries
16+
- Loops and conditionals
17+
- Input validation
18+
"""
19+
20+
import os # Used to check file existence and handle deletions
21+
22+
# Utility Functions
23+
24+
25+
def load_contacts():
26+
"""Reads all contacts from 'contacts.txt' and returns them as a list of dictionaries."""
27+
contacts = []
28+
if os.path.exists("contacts.txt"):
29+
with open("contacts.txt", "r") as file:
30+
for line in file:
31+
name, phone, email = line.strip().split("|")
32+
contacts.append({"name": name, "phone": phone, "email": email})
33+
return contacts
34+
35+
36+
def save_contacts(contacts):
37+
"""Saves all contacts to 'contacts.txt'."""
38+
with open("contacts.txt", "w") as file:
39+
for c in contacts:
40+
file.write(f"{c['name']}|{c['phone']}|{c['email']}\n")
41+
42+
43+
44+
# Core Functionality
45+
46+
47+
def add_contact(contacts):
48+
"""Adds a new contact to the list and saves it."""
49+
name = input("Enter contact name: ").strip()
50+
phone = input("Enter phone number: ").strip()
51+
email = input("Enter email address: ").strip()
52+
53+
if not name or not phone:
54+
print("Name and phone number are required!")
55+
return
56+
57+
contacts.append({"name": name, "phone": phone, "email": email})
58+
save_contacts(contacts)
59+
print(f"Contact '{name}' added successfully.\n")
60+
61+
62+
def view_contacts(contacts):
63+
"""Displays all contacts."""
64+
if not contacts:
65+
print("No contacts found.\n")
66+
return
67+
68+
print("\nYour Contacts:")
69+
print("-" * 40)
70+
for i, c in enumerate(contacts, start=1):
71+
print(f"{i}. Name: {c['name']}")
72+
print(f" Phone: {c['phone']}")
73+
print(f" Email: {c['email']}\n")
74+
print("-" * 40)
75+
76+
77+
def search_contact(contacts):
78+
"""Searches for a contact by name or phone number."""
79+
keyword = input("Enter name or phone number to search: ").strip().lower()
80+
results = [c for c in contacts if keyword in c["name"].lower() or keyword in c["phone"]]
81+
82+
if not results:
83+
print("No matching contacts found.\n")
84+
return
85+
86+
print("\nSearch Results:")
87+
print("-" * 40)
88+
for c in results:
89+
print(f"Name: {c['name']}")
90+
print(f"Phone: {c['phone']}")
91+
print(f"Email: {c['email']}\n")
92+
print("-" * 40)
93+
94+
95+
def delete_contact(contacts):
96+
"""Deletes a contact by name."""
97+
name = input("Enter the name of the contact to delete: ").strip().lower()
98+
for c in contacts:
99+
if c["name"].lower() == name:
100+
contacts.remove(c)
101+
save_contacts(contacts)
102+
print(f"Contact '{c['name']}' deleted successfully.\n")
103+
return
104+
print("Contact not found.\n")
105+
106+
107+
# Main Application Loop
108+
109+
110+
def main():
111+
"""Main menu loop."""
112+
contacts = load_contacts()
113+
114+
while True:
115+
print("""
116+
CONTACT BOOK =========
117+
1. View all contacts
118+
2. Add a new contact
119+
3. Search for a contact
120+
4. Delete a contact
121+
5. Exit
122+
)
123+
choice = input("Enter your choice (1-5): ").strip()
124+
125+
if choice == "1":
126+
view_contacts(contacts)
127+
elif choice == "2":
128+
add_contact(contacts)
129+
elif choice == "3":
130+
search_contact(contacts)
131+
elif choice == "4":
132+
delete_contact(contacts)
133+
elif choice == "5":
134+
print("Goodbye! Your contacts are saved.")
135+
break
136+
else:
137+
print("Invalid choice. Please select between 1 and 5.\n")
138+
139+
140+
# Run the program
141+
if __name__ == "__main__":
142+
main()

0 commit comments

Comments
 (0)