Question: How do I add exception handling if these are my inputs? command: view number: 2 ( invalid contact number ) Command: view Number x: (

How do I add exception handling if these are my inputs?
command: view
number: 2(invalid contact number)
Command: view
Number x: (Invalid integer)
Command: del
Number: 0(invalid contact numbers)
Command: del
Number: =(invalid integer)
Command: list (There are no contacts in the list)
Command: view (There are no contacts in the list)
Command: del (There are no contacts in the list)
Command: exit (Bye!)
Here's what I have so far:
import csv
import os
contacts =[]
import csv
import os
if not os.path.isfile('contacts.csv'):
with open('contacts.csv','w', newline='') as file:
writer = csv.writer(file)
print('contacts.csv file not found. A new file has been created.')
else:
print('contacts.csv file found.')
def load_contacts():
contacts =[]
try:
with open('contacts.csv', mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
contacts.append(row)
print("Contacts file loaded.")
except FileNotFoundError:
print("Could not find contacts file!")
print("Creating new contacts file...")
return contacts
# Function to save contacts to the CSV file
def save_contacts(contacts):
with open('contacts.csv', mode='w', newline='') as file:
fieldnames =['Name', 'Email', 'Phone']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for contact in contacts:
writer.writerow(contact)
# Function to display the command menu
def display_menu():
print("
COMMAND MENU")
print("list Display all contacts")
print("view View a contact")
print("add Add a contact")
print("del Delete a contact")
print("exit Exit program")
# Function to display all contacts
def list_contacts(contacts):
if not contacts:
print("No contacts to display.")
else:
for i, contact in enumerate(contacts, start=1):
print(f"{i}.{contact['Name']}")
# Function to view a specific contact
def view_contact(contacts):
try:
number = int(input("Number: "))
contact = contacts[number -1]
print(f"Name: {contact['Name']}")
print(f"Email: {contact['Email']}")
print(f"Phone: {contact['Phone']}")
except (ValueError, IndexError):
print("Invalid contact number.")
# Function to add a contact
def add_contact(contacts):
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
contacts.append({'Name': name, 'Email': email, 'Phone': phone})
save_contacts(contacts)
print(f"{name} was added.")
# Function to delete a contact
def delete_contact(contacts):
try:
number = int(input("Number: "))
contact = contacts.pop(number -1)
save_contacts(contacts)
print(f"{contact['Name']} was deleted.")
except (ValueError, IndexError):
print("Invalid contact number.")
# Main function to run the program
def main():
contacts = load_contacts()
display_menu()
while True:
command = input("
Command: ").lower()
if command == "list":
list_contacts(contacts)
elif command == "view":
view_contact(contacts)
elif command == "add":
add_contact(contacts)
elif command == "del":
delete_contact(contacts)
elif command == "exit":
break
else:
print("Invalid command. Try again.")
display_menu()
# Start the program
if __name__=="__main__":
main()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!