Basic Code 5
Basic Code 5
Your Name
March 24, 2025
1 Introduction
This document presents a simple Python-based Contact Book. Users can add,
view, search, and delete contacts using this program.
2 Python Code
1 import json
2
3 CONTACTS_FILE = " contacts . json "
4
5 def load_contacts () :
6 try :
7 with open ( CONTACTS_FILE , " r " ) as file :
8 return json . load ( file )
9 except ( FileNotFoundError , json . JS O ND ec o de Er ro r ) :
10 return {}
11
12 def save_contacts ( contacts ) :
13 with open ( CONTACTS_FILE , " w " ) as file :
14 json . dump ( contacts , file , indent =4)
15
16 def add_contact ( contacts ) :
17 name = input ( " Enter contact name : " ) . strip ()
18 phone = input ( " Enter phone number : " ) . strip ()
19 email = input ( " Enter email ( optional ) : " ) . strip ()
20
21 if name and phone :
22 contacts [ name ] = { " phone " : phone , " email " : email }
23 save_contacts ( contacts )
24 print ( f " Contact ’{ name } ’ added successfully !\ n " )
25 else :
26 print ( " Name and phone number are required !\ n " )
27
28 def view_contacts ( contacts ) :
29 if not contacts :
30 print ( " \ n No contacts available !\ n " )
31 else :
32 print ( " \ n Contact List : " )
33 for name , details in contacts . items () :
1
34 print ( f " { name } - { details [ ’ phone ’]} -
{ details [ ’ email ’]} " )
35 print ()
36
37 def search_c ontact ( contacts ) :
38 search_name = input ( " Enter name to search : " ) . strip ()
39 if search_name in contacts :
40 details = contacts [ search_name ]
41 print ( f " \ n Found : { search_name } - { details [ ’ phone
’]} - { details [ ’ email ’]}\ n " )
42 else :
43 print ( " Contact not found !\ n " )
44
45 def delete_c ontact ( contacts ) :
46 name = input ( " Enter name to delete : " ) . strip ()
47 if name in contacts :
48 del contacts [ name ]
49 save_contacts ( contacts )
50 print ( f " Contact ’{ name } ’ deleted !\ n " )
51 else :
52 print ( " Contact not found !\ n " )
53
54 def main () :
55 contacts = load_contacts ()
56
57 while True :
58 print ( " \ n Contact Book Menu : " )
59 print ( " 1 View Contacts " )
60 print ( " 2 Add Contact " )
61 print ( " 3 Search Contact " )
62 print ( " 4 Delete Contact " )
63 print ( " 5 Exit " )
64
65 choice = input ( " Choose an option (1 -5) : " ) . strip ()
66
67 if choice == " 1 " :
68 view_contacts ( contacts )
69 elif choice == " 2 " :
70 add_contact ( contacts )
71 elif choice == " 3 " :
72 sear ch_conta ct ( contacts )
73 elif choice == " 4 " :
74 dele te_conta ct ( contacts )
75 elif choice == " 5 " :
76 print ( " Exiting Contact Book . Have a great day !\ n
")
77 break
78 else :
79 print ( " Invalid option ! Please try again .\ n " )
80
81 if __name__ == " __main__ " :
82 main ()