Need some help with this Contact Manager Program

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 996 Views - Last Post: 20 March 2019 - 04:46 PM Rate Topic: -----

#16 gneisler   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 45
  • Joined: 23-September 11

Re: Need some help with this Contact Manager Program

Posted 11 March 2019 - 09:13 AM

The program is finally working, thanks, guys.
Was This Post Helpful? 0
  • +
  • -

#17 gneisler   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 45
  • Joined: 23-September 11

Re: Need some help with this Contact Manager Program

Posted 19 March 2019 - 09:37 AM

to add exception handling to this program. If the program canít find the CSV file, it should display an appropriate message and create a new CSV file that doesnít contain any contact data. For the view and del commands, display an appropriate error message if the user enters an invalid integer or an invalid contact number. Thank you, for your help.

import csv
import sys

FILENAME = "contacts.csv"

def exit_program():
    print("Terminating program.")
    sys.exit()

def read_contacts():
    try:
        movies = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                contacts.append(row)
        return contacts
    except FileNotFoundError as e:
       print("Could not find " + FILENAME + " file.")
       exit_program()
       return contacts
    except Exception as e:
        print(type(e), e)
        exit_program()
            
    
def write_contacts(contacts):
    try:
        with open (FILENAME, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerows(contacts)
            
    except OSError as e:
        print(type(e), e)
        exit_program()
    except Exception as e:
        print(type(e), e)
        exit_program()
              
     
def list_contacts(contacts):
    for i in range(0, len(contacts)):
        contact = contacts[i]
        print(str(i+1) + ". " + contact[0]+". " +  contact[1]  + "(" + str(contact[2]) +")" )
        print()

def view_contacts(contacts):
    while True:
        try:
            number = int(input("Number: "))
            
        except ValueError:
            print("Invalid integer. Please try again.")
            continue
    
    if number < 1 or number > len (contacts):
        print("Invalid contact number")
        print()
    else:

                 
            contact = contacts[number-1]
            print("Name: " + contact[0])
            print("Email: " + contact[1])
            print("Phone: " + contact[2])
            print()


def add_contacts(contacts):
    name = input("Name: ")
    email = input("Email: ")
    phone = input("Phone: ")
    contact = []
    contact.append(name)
    contact.append(email)
    contact.append(phone)
    contacts.append(contact)
    write_contacts(contacts)
    print(name + " was added")
    print()
    

def delete_contacts(contacts):
    while True:
        try:
            number = int(input("Number: "))
        except ValueError:
            print("Invalid integer.")
            continue
                  
                  
        if number < 0 or number > len (contacts):
            print("invalid number")

                      
        else:
           break
        contact = contacts.pop(number-1)
        write_contacts(contacts)
        print(contact[0] + " was deleted")
        
        
def display_menu():
    
    print("Contact Manager")
    print()
    print("COMMAND MENU")
    print("list - Display all contacts", "\nview - View a contact",
          "\nadd - Add a contact", "\ndel - Delete a contact",
          "\nexit - Exit program")
         
    print()
    
##definition main menu
def main():
    
    
    display_menu()
    contacts =  read_contacts()
    while True:
        command = input("Command: ")
        if command.lower() == "list":
            list_contacts(contacts)
        elif command.lower() == "view":
            view_contacts(contacts)
        elif command.lower() == "add":
            add_contacts(contacts)
        elif command.lower() == "del":
            delete_contacts(contacts)
        elif command.lower() == "exit":
            print("Good bye!")
            break
        else:
            print("Invalid command. Please try again.\n")
                           
if __name__ == "__main__":
    main()



Was This Post Helpful? 0
  • +
  • -

#18 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: Need some help with this Contact Manager Program

Posted 19 March 2019 - 10:14 AM

I'm getting an exception right when the program loads <class 'NameError'> name 'contacts' is not defined..

I resolved it by instantiating a contacts array [] right after FILENAME

contacts = []
Was This Post Helpful? 0
  • +
  • -

#19 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: Need some help with this Contact Manager Program

Posted 19 March 2019 - 10:21 AM

and you've already done most of that... all you would need to do is add a file if it doesn't exist inside your except

f=open(FILENAME,"w+") w+ parameter writes the file if it doesn't exist

def read_contacts():
    try:
        movies = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                contacts.append(row)
        return contacts
    except FileNotFoundError as e:
       print("Could not find " + FILENAME + " file.")
       f=open(FILENAME,"w+")
       return contacts
    except Exception as e:
        print(type(e), e)
        exit_program()
            
    


Was This Post Helpful? 0
  • +
  • -

#20 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2791
  • View blog
  • Posts: 11,004
  • Joined: 03-December 12

Re: Need some help with this Contact Manager Program

Posted 19 March 2019 - 10:24 AM

This will be a problem,


    except FileNotFoundError as e:
       print("Could not find " + FILENAME + " file.")
       exit_program()
       return contacts




def exit_program():
    print("Terminating program.")
    sys.exit()




Just as an aside.
Was This Post Helpful? 0
  • +
  • -

#21 gneisler   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 45
  • Joined: 23-September 11

Re: Need some help with this Contact Manager Program

Posted 20 March 2019 - 10:08 AM

having a problem when I enter the list if there are contacts in the list: There are no contacts in the list. is to be displayed and when and the invalid contact number statement is not displaying, for the view part. I thought python was to suppose to be an easy language.

import csv
import sys

FILENAME = "contacts.csv"


def read_contacts():
    try:
        contacts = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                contacts.append(row)
        return contacts
    except FileNotFoundError as e:
       print("Could not find " + FILENAME + " file.")
       f=open(FILENAME, "w+")
       
       return contacts
    except Exception as e:
        print(type(e), e)
        exit_program()
            
    
def write_contacts(contacts):
    try:
        with open (FILENAME, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerows(contacts)
            
    except OSError as e:
        print(type(e), e)
        exit_program()
    except Exception as e:
        print(type(e), e)
        exit_program()
              
     
def list_contacts(contacts):
    if len(contact) == 0:
        print("There are no contacts in the list.\n")
        return
    else:
        
        for i in range(0, len(contacts)):
            contact = contacts[i]
            print(str(i+1) + ". " + contact[0]+ "(" + str(contact[1]) +")" )
            
            print()

def view_contacts(contacts):
    while True:
        try:
            number = int(input("Number: "))
            
            
        except ValueError:
            print("Invalid integer. Please try again.")
            continue
    
    if number < 1 or number > len (contacts):
        print("Invalid contact number")
        print()
    else:

                 
            contact = contacts[number-1]
            print("Name: " + contact[0])
            print("Email: " + contact[1])
            print("Phone: " + contact[2])
            print()


def add_contacts(contacts):
    name = input("Name: ")
    email = input("Email: ")
    phone = input("Phone: ")
    contact = []
    contact.append(name)
    contact.append(email)
    contact.append(phone)
    contacts.append(contact)
    write_contacts(contacts)
    print(name + " was added")
    print()
    

def delete_contacts(contacts):
    while True:
        try:
            number = int(input("Number: "))
        except ValueError:
            print("Invalid integer.")
            continue
                  
                  
        if number < 0 or number > len (contacts):
            print("invalid number")

                      
        else:
           break
        contact = contacts.pop(number-1)
        write_contacts(contacts)
        print(contact[0] + " was deleted")
        
        
def display_menu():
    
    print("Contact Manager")
    print()
    print("COMMAND MENU")
    print("list - Display all contacts", "\nview - View a contact",
          "\nadd - Add a contact", "\ndel - Delete a contact",
          "\nexit - Exit program")
         
    print()
    
##definition main menu
def main():
    
    
    display_menu()
    contacts =  read_contacts()
    while True:
        command = input("Command: ")
        if command.lower() == "list":
            list_contacts(contacts)
        elif command.lower() == "view":
            view_contacts(contacts)
        elif command.lower() == "add":
            add_contacts(contacts)
        elif command.lower() == "del":
            delete_contacts(contacts)
        elif command.lower() == "exit":
            print("Good bye!")
            break
        else:
            print("Invalid command. Please try again.\n")
                           
if __name__ == "__main__":
    main()


Was This Post Helpful? 0
  • +
  • -

#22 hexagod   User is offline

  • 😂😂😂
  • member icon

Reputation: 31
  • View blog
  • Posts: 577
  • Joined: 29-October 16

Re: Need some help with this Contact Manager Program

Posted 20 March 2019 - 10:48 AM

You are trying to find the length of contact before it's defined... take a look at this code block and see if you can figure it out.

def list_contacts(contacts):
    #either get rid of this conditional, replace with a try except
    #or completely change the order of your definition
    if len(contact) == 0:
        print("There are no contacts in the list.\n")
        return
    else:
        
        for i in range(0, len(contacts)):
            #look below, this comes AFTER your conditional
            contact = contacts[i]
            print(str(i+1) + ". " + contact[0]+ "(" + str(contact[1]) +")" )
            
            print()




I'm too busy to completely retool your code but one option is simply remove the conditional and do it like this, not the greatest.. you should reorder your definition.

def list_contacts(contacts):
    try:
        for i in range(0, len(contacts)):
            contact = contacts[i]
            print(str(i+1) + ". " + contact[0]+ "(" + str(contact[1]) +")" )
            print()
    except:
        try:
            if len(contact) == 0:
                print("There are no contacts in the list.\n")
            else:
                print(type(e), e)
                return
        except:
            print(type(e), e)
            return




Attached Image

This post has been edited by hexagod: 20 March 2019 - 10:53 AM

Was This Post Helpful? 0
  • +
  • -

#23 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 513
  • View blog
  • Posts: 1,632
  • Joined: 27-December 13

Re: Need some help with this Contact Manager Program

Posted 20 March 2019 - 12:07 PM

This is not contributing directly to the problem in this thread; - rather it is about pythonic code style.

You use this construction:
def list_contacts(contacts):
    try:
        for i in range(0, len(contacts)):
            contact = contacts[i]
            print(str(i+1) + ". " + contact[0]+ "(" + str(contact[1]) +")" )
            print()


It is much more pythonic to write like this:
def list_contacts(contacts):
    try:
        for num, contact in enumerate(contacts):
            print(str(num+1) + ". " + contact[0]+ "(" + str(contact[1]) +")" )
            print()


Also, the print statement can be improved:
print("{}. {}({})".format(num+1, *contact))

or, maybe more readable:

print("{0}. {1}({2})".format(num+1, *contact))


I'm not trying to be pedantic; but you say you try to learn python and using python idioms definitely is part of it...
Was This Post Helpful? 0
  • +
  • -

#24 gneisler   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 45
  • Joined: 23-September 11

Re: Need some help with this Contact Manager Program

Posted 20 March 2019 - 04:46 PM

Thank You, everyone, for your assistance.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2