-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontact_book_system.py
More file actions
844 lines (701 loc) · 30.7 KB
/
contact_book_system.py
File metadata and controls
844 lines (701 loc) · 30.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# import os
# import re
# class Contact:
# def __init__(self, name, phone, email):
# self.name = name
# self.phone = phone
# self.email = email
# def __str__(self):
# return f"Name: {self.name}, Phone: {self.phone}, Email: {self.email}"
# class ContactBook:
# def __init__(self, filename="contacts.txt"):
# self.filename = filename
# self.contacts = self.load_contacts()
# def load_contacts(self):
# """Load contacts from file with error handling"""
# contacts = {}
# if os.path.exists(self.filename):
# try:
# with open(self.filename, 'r') as file:
# for line in file:
# line = line.strip()
# if line: # Skip empty lines
# try:
# name, phone, email = line.split(",")
# contacts[name.lower()] = Contact(name.strip(), phone.strip(), email.strip())
# except ValueError:
# print(f"[Warning] Skipping malformed line: {line}")
# except Exception as e:
# print(f"[Error] Failed to load contacts: {e}")
# return contacts
# def save_contacts(self):
# """Save contacts to file atomically"""
# try:
# temp_file = self.filename + ".tmp"
# with open(temp_file, 'w') as file:
# for contact in sorted(self.contacts.values(), key=lambda x: x.name):
# file.write(f"{contact.name},{contact.phone},{contact.email}\n")
# # Atomic file operation
# if os.path.exists(self.filename):
# os.replace(temp_file, self.filename)
# else:
# os.rename(temp_file, self.filename)
# except Exception as e:
# print(f"[Error] Failed to save contacts: {e}")
# if os.path.exists(temp_file):
# os.remove(temp_file)
# def add_contact(self, name, phone, email):
# """Add a new contact with validation"""
# name_key = name.lower()
# if name_key in self.contacts:
# print(f"[Error] Contact '{name}' already exists!")
# return False
# if not self.is_valid_phone(phone):
# print("[Error] Invalid phone number. Must be 10 digits.")
# return False
# if not self.is_valid_email(email):
# print("[Error] Invalid email format. Should be like 'example@domain.com'")
# return False
# self.contacts[name_key] = Contact(name, phone, email)
# self.save_contacts()
# print(f"[Success] Contact '{name}' added successfully!")
# return True
# def update_contact(self, name, phone=None, email=None):
# """Update existing contact details"""
# name_key = name.lower()
# if name_key not in self.contacts:
# print(f"[Error] Contact '{name}' not found!")
# return False
# contact = self.contacts[name_key]
# if phone and not self.is_valid_phone(phone):
# print("[Error] Invalid phone number. Must be 10 digits.")
# return False
# if email and not self.is_valid_email(email):
# print("[Error] Invalid email format. Should be like 'example@domain.com'")
# return False
# if phone:
# contact.phone = phone
# if email:
# contact.email = email
# self.save_contacts()
# print(f"[Success] Contact '{name}' updated successfully!")
# return True
# def delete_contact(self, name):
# """Delete a contact"""
# name_key = name.lower()
# if name_key in self.contacts:
# del self.contacts[name_key]
# self.save_contacts()
# print(f"[Success] Contact '{name}' deleted successfully!")
# return True
# else:
# print(f"[Error] Contact '{name}' not found!")
# return False
# def search_contact(self, name):
# """Search for a contact by name"""
# name_key = name.lower()
# if name_key in self.contacts:
# print("\n--- Contact Found ---")
# print(self.contacts[name_key])
# print("--------------------")
# return True
# else:
# print(f"[Info] No contact found for '{name}'")
# return False
# def list_contacts(self):
# """List all contacts alphabetically"""
# if not self.contacts:
# print("[Info] No contacts available.")
# return
# print("\n--- All Contacts ---")
# for contact in sorted(self.contacts.values(), key=lambda x: x.name):
# print(contact)
# print(f"Total: {len(self.contacts)} contacts")
# print("-------------------")
# @staticmethod
# def is_valid_phone(phone):
# """Validate phone number (10 digits)"""
# cleaned = ''.join(c for c in phone if c.isdigit())
# return len(cleaned) == 10
# @staticmethod
# def is_valid_email(email):
# """Basic email validation"""
# return re.match(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", email) is not None
# def print_menu():
# """Display the main menu"""
# print("\n" + "="*40)
# print("CONTACT BOOK MANAGEMENT SYSTEM".center(40))
# print("="*40)
# print("1. Add New Contact")
# print("2. Update Existing Contact")
# print("3. Delete Contact")
# print("4. Search Contact")
# print("5. List All Contacts")
# print("6. Exit")
# print("="*40)
# def get_input(prompt, required=True):
# """Get user input with validation"""
# while True:
# value = input(prompt).strip()
# if not value and required:
# print("[Error] This field is required!")
# continue
# return value
# def main():
# contact_book = ContactBook()
# while True:
# print_menu()
# choice = get_input("Enter your choice (1-6): ")
# if choice == '1': # Add Contact
# print("\n--- Add New Contact ---")
# name = get_input("Name: ")
# phone = get_input("Phone (10 digits): ")
# email = get_input("Email: ")
# contact_book.add_contact(name, phone, email)
# elif choice == '2': # Update Contact
# print("\n--- Update Contact ---")
# name = get_input("Name of contact to update: ")
# if contact_book.search_contact(name):
# phone = get_input("New phone (press Enter to keep current): ", required=False)
# email = get_input("New email (press Enter to keep current): ", required=False)
# if not phone and not email:
# print("[Info] No changes made.")
# else:
# contact_book.update_contact(name, phone or None, email or None)
# elif choice == '3': # Delete Contact
# print("\n--- Delete Contact ---")
# name = get_input("Name of contact to delete: ")
# contact_book.delete_contact(name)
# elif choice == '4': # Search Contact
# print("\n--- Search Contact ---")
# name = get_input("Name to search: ")
# contact_book.search_contact(name)
# elif choice == '5': # List Contacts
# contact_book.list_contacts()
# elif choice == '6': # Exit
# print("\n[Info] Thank you for using Contact Book!")
# print("Exiting the program...")
# break
# else:
# print("[Error] Invalid choice! Please enter 1-6.")
# if __name__ == "__main__":
# main()
"""
import json
import os
import re
import getpass
from datetime import datetime
class Contact:
def __init__(self, name, phone, email, country_code="+1"):
self.name = name
self.phone = phone
self.email = email
self.country_code = country_code
def __str__(self):
return f"Name: {self.name}, Phone: {self.country_code}{self.phone}, Email: {self.email}"
def to_dict(self):
return {
"name": self.name,
"phone": self.phone,
"email": self.email,
"country_code": self.country_code
}
@staticmethod
def from_dict(data):
return Contact(
data["name"],
data["phone"],
data["email"],
data.get("country_code", "+1")
)
class ContactBook:
def __init__(self, filename="contacts.json"):
self.filename = filename
self.contacts = self.load_contacts()
self.country_codes = {
"US": "+1", "UK": "+44", "IN": "+91",
"AU": "+61", "DE": "+49", "FR": "+33"
}
def load_contacts(self):
if not os.path.exists(self.filename):
return {}
try:
with open(self.filename, 'r') as file:
data = json.load(file)
return {contact["name"]: Contact.from_dict(contact) for contact in data}
except Exception as e:
print(f"Error loading contacts: {e}")
return {}
def save_contacts(self):
try:
with open(self.filename, 'w') as file:
json.dump([contact.to_dict() for contact in self.contacts.values()],
file, indent=2)
except Exception as e:
print(f"Error saving contacts: {e}")
def add_contact(self, contact):
if contact.name in self.contacts:
print(f"Contact '{contact.name}' already exists!")
return False
self.contacts[contact.name] = contact
self.save_contacts()
print(f"Contact '{contact.name}' added successfully!")
return True
def update_contact(self, name, **kwargs):
if name not in self.contacts:
print(f"Contact '{name}' not found!")
return False
contact = self.contacts[name]
for key, value in kwargs.items():
if value: # Only update if value is provided
setattr(contact, key, value)
self.save_contacts()
print(f"Contact '{name}' updated successfully!")
return True
def delete_contact(self, name):
if name not in self.contacts:
print(f"Contact '{name}' not found!")
return False
del self.contacts[name]
self.save_contacts()
print(f"Contact '{name}' deleted successfully!")
return True
def search_contacts(self, query):
results = []
query = query.lower()
for contact in self.contacts.values():
if (query in contact.name.lower() or
query in contact.phone or
query in contact.email.lower()):
results.append(contact)
return results
def list_contacts(self, sort_by="name"):
return sorted(
self.contacts.values(),
key=lambda x: getattr(x, sort_by.lower())
)
def backup_contacts(self, backup_file=None):
backup_file = backup_file or f"contacts_backup_{datetime.now().strftime('%Y%m%d')}.json"
try:
with open(backup_file, 'w') as file:
json.dump([contact.to_dict() for contact in self.contacts.values()],
file, indent=2)
print(f"Backup created successfully at {backup_file}")
return True
except Exception as e:
print(f"Backup failed: {e}")
return False
@staticmethod
def validate_phone(phone):
return bool(re.match(r'^\d{10,15}$', phone))
@staticmethod
def validate_email(email):
return bool(re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email))
def get_country_code(self):
print("\nAvailable Country Codes:")
for code, prefix in self.country_codes.items():
print(f"{code}: {prefix}")
while True:
choice = input("Enter country code (e.g., US, UK) or custom prefix (e.g., +33): ").upper()
if choice in self.country_codes:
return self.country_codes[choice]
elif re.match(r'^\+\d{1,3}$', choice):
return choice
print("Invalid country code! Try again.")
def print_menu():
print("\n" + "="*50)
print("ADVANCED CONTACT BOOK MANAGEMENT SYSTEM".center(50))
print("="*50)
print("1. Add New Contact")
print("2. Update Contact")
print("3. Delete Contact")
print("4. Search Contacts")
print("5. List All Contacts")
print("6. Create Backup")
print("7. Exit")
print("="*50)
def authenticate():
password = getpass.getpass("Enter admin password: ")
return password == "admin123" # Change this in production!
def get_contact_details(contact_book):
name = input("Enter full name: ").strip()
while not name:
print("Name cannot be empty!")
name = input("Enter full name: ").strip()
country_code = contact_book.get_country_code()
phone = input(f"Enter phone number (without {country_code}): ").strip()
while not contact_book.validate_phone(phone):
print("Invalid phone number! Must be 10-15 digits.")
phone = input(f"Enter phone number (without {country_code}): ").strip()
email = input("Enter email address: ").strip()
while not contact_book.validate_email(email):
print("Invalid email address!")
email = input("Enter email address: ").strip()
return Contact(name, phone, email, country_code)
def main():
if not authenticate():
print("Authentication failed!")
return
contact_book = ContactBook()
while True:
print_menu()
choice = input("Enter your choice (1-7): ").strip()
if choice == '1': # Add Contact
contact = get_contact_details(contact_book)
contact_book.add_contact(contact)
elif choice == '2': # Update Contact
name = input("Enter name of contact to update: ").strip()
if name in contact_book.contacts:
print("\nLeave blank to keep current value")
country_code = input(f"New country code [current: {contact_book.contacts[name].country_code}]: ").strip()
phone = input(f"New phone [current: {contact_book.contacts[name].phone}]: ").strip()
email = input(f"New email [current: {contact_book.contacts[name].email}]: ").strip()
updates = {}
if country_code:
updates["country_code"] = contact_book.get_country_code() if country_code.upper() == "CHOOSE" else country_code
if phone:
updates["phone"] = phone
if email:
updates["email"] = email
contact_book.update_contact(name, **updates)
else:
print(f"Contact '{name}' not found!")
elif choice == '3': # Delete Contact
name = input("Enter name of contact to delete: ").strip()
contact_book.delete_contact(name)
elif choice == '4': # Search Contacts
query = input("Enter search term: ").strip()
results = contact_book.search_contacts(query)
if results:
print("\n=== Search Results ===")
for contact in results:
print(contact)
print(f"Found {len(results)} contacts")
else:
print("No matching contacts found")
elif choice == '5': # List Contacts
sort_by = input("Sort by (name/phone/email/country_code): ").strip().lower()
contacts = contact_book.list_contacts(sort_by if sort_by in ["name", "phone", "email", "country_code"] else "name")
print("\n=== All Contacts ===")
for contact in contacts:
print(contact)
print(f"Total: {len(contacts)} contacts")
elif choice == '6': # Backup
backup_file = input("Enter backup filename (press Enter for default): ").strip()
contact_book.backup_contacts(backup_file if backup_file else None)
elif choice == '7': # Exit
print("Exiting contact book. Goodbye!")
break
else:
print("Invalid choice! Please enter 1-7")
if __name__ == "__main__":
main()"
"""
import json
import os
import re
import getpass
from datetime import datetime
class Contact:
def __init__(self, name, phone, email, country_code="+1", job_title=None, salary=None):
self.name = name
self.phone = phone
self.email = email
self.country_code = country_code
self.job_title = job_title
self.salary = salary
self.last_updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def __str__(self):
salary_info = f", Salary: ${self.salary:,.2f}" if self.salary else ""
job_info = f", Position: {self.job_title}" if self.job_title else ""
return (f"Name: {self.name}, Phone: {self.country_code}{self.phone}, "
f"Email: {self.email}{job_info}{salary_info}, "
f"Last Updated: {self.last_updated}")
def to_dict(self):
return {
"name": self.name,
"phone": self.phone,
"email": self.email,
"country_code": self.country_code,
"job_title": self.job_title,
"salary": self.salary,
"last_updated": self.last_updated
}
@staticmethod
def from_dict(data):
return Contact(
data["name"],
data["phone"],
data["email"],
data.get("country_code", "+1"),
data.get("job_title"),
data.get("salary")
)
class ContactBook:
def __init__(self, filename="contacts.json"):
self.filename = filename
self.contacts = self.load_contacts()
self.country_codes = {
"US": "+1", "UK": "+44", "IN": "+91",
"AU": "+61", "DE": "+49", "FR": "+33",
"JP": "+81", "BR": "+55", "CN": "+86"
}
self.job_categories = [
"Manager", "Developer", "Designer",
"Analyst", "Director", "Engineer",
"Consultant", "Other"
]
def load_contacts(self):
if not os.path.exists(self.filename):
return {}
try:
with open(self.filename, 'r') as file:
data = json.load(file)
return {contact["name"]: Contact.from_dict(contact) for contact in data}
except Exception as e:
print(f"Error loading contacts: {e}")
return {}
def save_contacts(self):
try:
with open(self.filename, 'w') as file:
json.dump([contact.to_dict() for contact in self.contacts.values()],
file, indent=2)
except Exception as e:
print(f"Error saving contacts: {e}")
def add_contact(self, contact):
if contact.name in self.contacts:
print(f"Contact '{contact.name}' already exists!")
return False
self.contacts[contact.name] = contact
self.save_contacts()
print(f"Contact '{contact.name}' added successfully!")
return True
def update_contact(self, name, **kwargs):
if name not in self.contacts:
print(f"Contact '{name}' not found!")
return False
contact = self.contacts[name]
for key, value in kwargs.items():
if value is not None: # Only update if value is provided
setattr(contact, key, value)
contact.last_updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.save_contacts()
print(f"Contact '{name}' updated successfully!")
return True
def delete_contact(self, name):
if name not in self.contacts:
print(f"Contact '{name}' not found!")
return False
del self.contacts[name]
self.save_contacts()
print(f"Contact '{name}' deleted successfully!")
return True
def search_contacts(self, query):
results = []
query = query.lower()
for contact in self.contacts.values():
if (query in contact.name.lower() or
query in contact.phone or
query in contact.email.lower() or
(contact.job_title and query in contact.job_title.lower())):
results.append(contact)
return results
def list_contacts(self, sort_by="name"):
valid_sort_fields = ["name", "phone", "email", "job_title", "salary", "last_updated"]
sort_by = sort_by if sort_by in valid_sort_fields else "name"
return sorted(
self.contacts.values(),
key=lambda x: str(getattr(x, sort_by)).lower()
)
def backup_contacts(self, backup_file=None):
backup_file = backup_file or f"contacts_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
try:
with open(backup_file, 'w') as file:
json.dump([contact.to_dict() for contact in self.contacts.values()],
file, indent=2)
print(f"Backup created successfully at {backup_file}")
return True
except Exception as e:
print(f"Backup failed: {e}")
return False
def get_job_stats(self):
stats = {
"total_contacts": len(self.contacts),
"jobs": {},
"salary_stats": {
"total": 0,
"average": 0,
"max": 0,
"min": float('inf')
}
}
salary_count = 0
total_salary = 0
for contact in self.contacts.values():
if contact.job_title:
stats["jobs"][contact.job_title] = stats["jobs"].get(contact.job_title, 0) + 1
if contact.salary:
salary_count += 1
total_salary += contact.salary
stats["salary_stats"]["max"] = max(stats["salary_stats"]["max"], contact.salary)
stats["salary_stats"]["min"] = min(stats["salary_stats"]["min"], contact.salary)
if salary_count > 0:
stats["salary_stats"]["total"] = total_salary
stats["salary_stats"]["average"] = total_salary / salary_count
stats["salary_stats"]["count"] = salary_count
else:
stats["salary_stats"]["min"] = 0
return stats
@staticmethod
def validate_phone(phone):
return bool(re.match(r'^\d{10,15}$', phone))
@staticmethod
def validate_email(email):
return bool(re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email))
@staticmethod
def validate_salary(salary):
try:
return float(salary) >= 0
except ValueError:
return False
def get_country_code(self):
print("\nAvailable Country Codes:")
for code, prefix in self.country_codes.items():
print(f"{code}: {prefix}")
while True:
choice = input("Enter country code (e.g., US, UK) or custom prefix (e.g., +33): ").upper()
if choice in self.country_codes:
return self.country_codes[choice]
elif re.match(r'^\+\d{1,3}$', choice):
return choice
print("Invalid country code! Try again.")
def get_job_title(self):
print("\nJob Categories:")
for i, category in enumerate(self.job_categories, 1):
print(f"{i}. {category}")
while True:
choice = input("Select job category (1-8) or enter custom title: ").strip()
if choice.isdigit() and 1 <= int(choice) <= len(self.job_categories):
return self.job_categories[int(choice)-1]
elif choice:
return choice.title()
print("Invalid selection!")
def print_menu():
print("\n" + "="*60)
print("PROFESSIONAL CONTACT BOOK WITH JOB TRACKING".center(60))
print("="*60)
print("1. Add New Contact")
print("2. Update Contact")
print("3. Delete Contact")
print("4. Search Contacts")
print("5. List All Contacts")
print("6. View Job Statistics")
print("7. Create Backup")
print("8. Exit")
print("="*60)
def authenticate():
password = getpass.getpass("Enter admin password: ")
return password == "secure123" # Change this in production!
def get_contact_details(contact_book):
name = input("Enter full name: ").strip()
while not name:
print("Name cannot be empty!")
name = input("Enter full name: ").strip()
country_code = contact_book.get_country_code()
phone = input(f"Enter phone number (without {country_code}): ").strip()
while not contact_book.validate_phone(phone):
print("Invalid phone number! Must be 10-15 digits.")
phone = input(f"Enter phone number (without {country_code}): ").strip()
email = input("Enter email address: ").strip()
while not contact_book.validate_email(email):
print("Invalid email address!")
email = input("Enter email address: ").strip()
job_title = contact_book.get_job_title()
salary = None
salary_input = input("Enter annual salary (leave empty if unknown): $").strip()
if salary_input:
while not contact_book.validate_salary(salary_input):
print("Invalid salary! Must be a positive number.")
salary_input = input("Enter annual salary: $").strip()
salary = float(salary_input)
return Contact(name, phone, email, country_code, job_title, salary)
def main():
if not authenticate():
print("Authentication failed! Access denied.")
return
contact_book = ContactBook()
while True:
print_menu()
choice = input("Enter your choice (1-8): ").strip()
if choice == '1': # Add Contact
contact = get_contact_details(contact_book)
contact_book.add_contact(contact)
elif choice == '2': # Update Contact
name = input("Enter name of contact to update: ").strip()
if name in contact_book.contacts:
print("\nLeave blank to keep current value")
print(f"[Current: {contact_book.contacts[name]}]")
updates = {}
if input("Update country code? (y/n): ").lower() == 'y':
updates["country_code"] = contact_book.get_country_code()
phone = input(f"New phone [current: {contact_book.contacts[name].phone}]: ").strip()
if phone:
updates["phone"] = phone
email = input(f"New email [current: {contact_book.contacts[name].email}]: ").strip()
if email:
updates["email"] = email
if input("Update job title? (y/n): ").lower() == 'y':
updates["job_title"] = contact_book.get_job_title()
salary = input(f"New salary [current: {contact_book.contacts[name].salary or 'Not set'}]: $").strip()
if salary:
updates["salary"] = float(salary)
contact_book.update_contact(name, **updates)
else:
print(f"Contact '{name}' not found!")
elif choice == '3': # Delete Contact
name = input("Enter name of contact to delete: ").strip()
contact_book.delete_contact(name)
elif choice == '4': # Search Contacts
query = input("Enter search term (name, phone, email, or job title): ").strip()
results = contact_book.search_contacts(query)
if results:
print("\n=== Search Results ===")
for contact in results:
print(contact)
print(f"Found {len(results)} contacts")
else:
print("No matching contacts found")
elif choice == '5': # List Contacts
sort_by = input("Sort by (name/phone/email/job_title/salary/last_updated): ").strip().lower()
contacts = contact_book.list_contacts(sort_by)
print("\n=== All Contacts ===")
for contact in contacts:
print(contact)
print(f"\nTotal: {len(contacts)} contacts")
print(f"Sorted by: {sort_by}")
elif choice == '6': # Job Statistics
stats = contact_book.get_job_stats()
print("\n=== Employment Statistics ===")
print(f"Total Contacts: {stats['total_contacts']}")
print(f"Contacts with Salary Data: {stats['salary_stats'].get('count', 0)}")
if stats['salary_stats']['count'] > 0:
print("\nSalary Statistics:")
print(f"Total Salary: ${stats['salary_stats']['total']:,.2f}")
print(f"Average Salary: ${stats['salary_stats']['average']:,.2f}")
print(f"Highest Salary: ${stats['salary_stats']['max']:,.2f}")
print(f"Lowest Salary: ${stats['salary_stats']['min']:,.2f}")
if stats['jobs']:
print("\nJob Title Distribution:")
for job, count in sorted(stats['jobs'].items(), key=lambda x: x[1], reverse=True):
print(f"{job}: {count} contacts")
elif choice == '7': # Backup
backup_file = input("Enter backup filename (press Enter for default): ").strip()
contact_book.backup_contacts(backup_file if backup_file else None)
elif choice == '8': # Exit
print("Exiting contact book. Goodbye!")
break
else:
print("Invalid choice! Please enter 1-8")
if __name__ == "__main__":
main()