Question

VELYIEW Design a program that you can use to keep information on your family or friends. You may view the video demonstration

language:python

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Summary :

Provided code for different options / menu mentioned .

Notes :

Included validation for name , phone numbe using regular expression , same can be extended if required for other fields or refined if required .

Delete - For this menu the matched contact is deleted . as it was not clear from the mentioned in above quesiton.

Python Code :

import re


class Contact :
    """
        define initialization function with default parameters - blank and zero for first name , last name & phone number respectively.
    """

    def __init__(self,fName="" , lName="",pNumber=0):
        self.firstName = fName
        self.lastName = lName
        self.phoneNumber = pNumber


    def getFirstName(self) :
        return self.firstName

    def getLastName(self):
        return self.lastName

    def getPhone(self):
        return self.phoneNumber

    def setFirstName(self,name):
        self.firstName = name

    def setLastName(self,name):
        self.lastName = name

    def setPhone(self,phone):
        self.phoneNumber = phone

    def __str__(self) :
        rstr = "Name : " + self.firstName + ", " + self.lastName + " ; Phone : " + str(self.phoneNumber )
        return rstr

    def readFirstName(self ) :
        """ This function reads input from User and validates using regular express whether input word only has alphabets
             then sets the values to First name and exits
             otherwise repeatedly prompts user for valid input
        """

        flag = True
        while ( flag ) :
            name = input("Enter First Name : ")
            if ( re.match("^[a-zA-Z]*$", name) ) :
               self.setFirstName(name)
               flag = False
            else :
                print("Enter Valid input ")


    def readLastName(self ) :
        flag = True
        while ( flag ) :
            name = input("Enter Last Name : ")
            if ( re.match("^[a-zA-Z]*$", name) ) :
               self.setLastName(name)
               flag = False
            else :
                print("Enter Valid input ")


    def readPhone(self) :
        flag = True
        while ( flag ) :
            name = input("Enter Phone Number : ")
            if ( re.match("^[0-9- ]*$", name) ) :
               self.setPhone(name)
               flag = False
            else :
                print("Enter Valid input ")

class Family(Contact) :

    def __init__(self,fName="",lName="",phone=0,relationship=""):
        super().__init__(fName,lName,phone)
        self.relationship = relationship

  
    def getRelation(self) :
        return self.relationship

    def setRelation(self,relation_str):
        self.relationship = relation_str


    def __str__(self) :
        return super().__str__() + " ; Relation : " + self.relationship


class Friend(Contact) :

    def __init__(self,fName="",lName="",phone=0,dateMet=0):
        super().__init__(fName,lName,phone)
        self.dateMet = dateMet

  
    def getDateMet(self) :
        return self.dateMet

    def setDateMet(self,dateM):
        self.dateMet = dateM


    def __str__(self) :
        return super().__str__() + " ; DateMet : " + self.dateMet

def readFamilyContacts(filename , contactType):
    fContacts = []
    if contactType == "family" :
        flname = "family.txt"
    elif contactType == "friend":
        flname = "friend.txt"
    else :
        print(" Invalid contact Type ")
        return []

    try :
        with open(flname, 'r') as file1:
            lines = file1.readlines()
          
            for line0 in lines :
                #print("Line ", line)
                line = line0.strip()
                fields = line.split(";")
                if ( len(fields) == 3 ) :
                    #print("Fields ", fields[0] , fields[1], fields[2])

                    name = fields[0].split(":")
                    names = name[1].split(",")
                    phoneNum = fields[1].split(":")
                    lastfield = fields[2].split(":")
                    #print("Names : ", names )
                    #print("Phone nUm " , phoneNum )
                    #print("Last field " , lastfield)
                    if contactType == "family" :
                        #relationShip = lastfield.split(":")
                        contact = Family(names[0],names[1],phoneNum[1],lastfield[1])
                        fContacts.append(contact)
                    if contactType == "friend" :
                        #dateMet = lastfield.split(":")
                        contact = Friend(names[0],names[1],phoneNum[1],lastfield[1])
                        fContacts.append(contact)

            return fContacts
    except(FileNotFoundError) :
        print("Input file not found ")
        return []

def showMenu(itype) :
    if ( itype == 1 ) :
        print("Choose from following :")
        print("   1.Add Contact")
        print("   2.Edit Contact")
        print("   3.Delete Contact")
        print("   4.View Contact")
        print("   5.Exit")
    else :
        print("Choose from following : ")
        print("   1. Family")
        print("   2. Friend")

def getChoice(itype) :
    flag = True
  
    ichoice = 0
    while(flag ) :
        try :
            input_str = input("Enter your Choice : ")
            ichoice = int(input_str)
            if ( itype == 1 ) :
                upper_limit = 5
            else :
                upper_limit = 2
            if ( ichoice < 1 ) or ( ichoice > upper_limit ):
                print(" Enter valid input , for eg 1 or " + str(upper_limit) )
            else :
                flag = False
                break
        except ValueError as e :
                print(" Enter valid input , for eg 1 or " + str(upper_limit) )

    return ichoice
  
      

def addContact() :
    """ This function doesn't take any parameters
        It prompts user for which type of contact to be created and then
        prompts for name , phonenum and other input
        creates a contact object and returns
    """

    showMenu(2)
    input_str = getChoice(2)
  
    contact_obj = None
    if ( input_str == 1 ) :
        contact_obj = Family()
        contact_obj.readFirstName()
        contact_obj.readLastName()
        contact_obj.readPhone()
        relation_str = input("Enter relationship : ")
        contact_obj.setRelation(relation_str)
    else :
        contact_obj = Friend()
        contact_obj.readFirstName()
        contact_obj.readLastName()
        contact_obj.readPhone()
        date_met = input("Enter Date Met : ")
        contact_obj.setDateMet(date_met)
    return contact_obj

def editContact(contacts) :
    """ This function takes contacts list as the input and prompts user to input the name of the contact
        and modify the contact
    """

    name = input("Enter the name of the Contact to be modified : ")

    modify_item = None
    for item in contacts :
        if ( name in item.getFirstName() or name in item.getLastName() ) :
            phone_num = input("Enter updated phone number : ")
            if ( len(phone_num) > 0 ) :
                item.setPhone(phone_num)

        # Check if the object type is Family or Friend and decide to udpate respectively
            if isinstance(item, Family ) :
                relation_str = input("Enter updated relationship : ")
                if ( len(relation_str) > 0 ) :
                    item.setRelation(relation_str)
            if isinstance(item, Friend ) :
                date_met = input("Enter updated date met : ")
                if ( len(date_met) > 0 ) :
                    item.setDateMet(date_met)
            break


def deleteContact(contacts) :
    """ This function takes contacts list as the input and prompts user to input the name of the contact
        and deletes the matched
    """

    name = input("Enter the name of the Contact to be Deleted : ")

    modify_item = None
    for item in contacts :
        if ( name in item.getFirstName() or name in item.getLastName() ) :
           contacts.remove(item)
           break

def storeContacts(contacts) :
  
    try :
        file1 = open("family.txt", 'w')
        file2 = open("friend.txt", 'w')
        for item in contacts :
        # Check if the object type is Family or Friend and decide to write respective files
            if ( isinstance(item,Family)):
                    file1.write(item.__str__() + "\n")
           if ( isinstance(item,Friend)):
                    file2.write(item.__str__() + "\n")
    except(FileNotFoundError) :
        print("Input file not found ")
        return []


if __name__ == '__main__':

    #b1 = Family("X1","x2",123456789,"Bro")
    #print( b1)

    #f1 = Friend("xk","kd",3432983928,"24/01/3993")
    #print(f1)

    family_list = readFamilyContacts("family.txt","family")
    friend_list = readFamilyContacts("friend.txt","friend")
    contacts_list = family_list + friend_list

    ip = 1
    while ( ip != 5 ) :
        showMenu(1)
        ip = getChoice(1)
        if ( ip == 1 ) :
          c_obj =   addContact()
          contacts_list.append(c_obj)

        if ( ip == 2 ) :
            editContact(contacts_list)

        if ( ip == 3 ) :
            deleteContact(contacts_list)
        if ( ip == 4 ) :
            for cnt in contacts_list :
                print( cnt )
        if ( ip == 5 ) :
            storeContacts(contacts_list)

Output :

usrODESKTOP-VUM52 6N:/mnt/i/PRJ/Code/pyth/misc/Cards $ python3 PhoneBook.py Choose from following: 1. Add Contact 2. Edit Con

Enter the name of the Contact to be modified : Pinky Enter updated phone number : 222222222 Enter updated relationship : Aunt

Name : James, Bond ; Phone : 1233333333; Relation : Uncle Choose from following : 1. Add Contact 2. Edit Contact 3. Delete Co

Add a comment
Know the answer?
Add Answer to:
language:python VELYIEW Design a program that you can use to keep information on your family or...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please help!! (C++ PROGRAM) You will design an online contact list to keep track of names...

    Please help!! (C++ PROGRAM) You will design an online contact list to keep track of names and phone numbers. ·         a. Define a class contactList that can store a name and up to 3 phone numbers (use an array for the phone numbers). Use constructors to automatically initialize the member variables. b.Add the following operations to your program: i. Add a new contact. Ask the user to enter the name and up to 3 phone numbers. ii. Delete a contact...

  • Problem: Contact Information Sometimes we need a program that have all the contact information like name,...

    Problem: Contact Information Sometimes we need a program that have all the contact information like name, last name, telephone, direction and something we need to know about that person (notes). Write a program in java language with GUI, classes, arrays, files and inheritance that make this possible. In the first layer, the user should see all the contacts and three buttons (add, delete, edit). *Add button: If the user click the button add, a new layer should appear and should...

  • a. Define the struct node that can store a name and up to 3 phone numbers...

    a. Define the struct node that can store a name and up to 3 phone numbers (use an array for the phone numbers). The node struct will also store the address to the next node. b. Define a class contactList that will define a variable to keep track of the number of contacts in the list, a pointer to the first and last node of the list. c. Add the following methods to the class: i. Add a new contact....

  • DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to...

    DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to add new phone contacts, display a list of all contacts, search for a specific contact by name, delete a specific contact. The program should provide the user with a console or command line choice menu about possible actions that they can perform. The choices should be the following: 1. Display list of all contacts. 2. Add a new contact. 3. Search for a contact...

  • This program is used to create a phonebook for storing contact information into a text file....

    This program is used to create a phonebook for storing contact information into a text file. The program begins by asking the user to provide a name for the file that will contain their phone book information. It will then ask the user to provide the names and numbers of their contacts. It should keep asking the user for contact information until they type in Done (case-sensitive). After the user types Done, store all contact information into the file name...

  • (JAVA) Using classes and inheritance, design an online address book to keep track of the names

    (JAVA)Using classes and inheritance, design an online address book to keep track of the names, addresses, phone numbers and birthdays of family members, friends and business associates. Your program should be able to handle a maximum of 500 entries.Define the following classes: Class Address to store a street name, city, state and zip code. Class Date to store the day, month and year. Class Person to store a person's last name and first name. Class ExtPerson that extends the class...

  • Requirements Create an Address Book class in Java for general use with the following behaviors: 1....

    Requirements Create an Address Book class in Java for general use with the following behaviors: 1. Constructor: public Address Book Construct a new address book object. • A contact has four fields: first name, last name, email and phone. (There could be more information for a real contact. But these are sufficient for the assignment.) . The constructor reads from the disk to retrieve previously entered contacts. If previous contacts exist, the address book will be populated with those contacts...

  • C++ In this assignment, you will write a class that implements a contact book entry. For...

    C++ In this assignment, you will write a class that implements a contact book entry. For example, my iPhone (and pretty much any smartphone) has a contacts list app that allows you to store information about your friends, colleagues, and businesses. In later assignments, you will have to implement this type of app (as a command line program, of course.) For now, you will just have to implement the building blocks for this app, namely, the Contact class. Your Contact...

  • Design a program using a RAPTOR flowchart that has two parallel arrays: a String array named...

    Design a program using a RAPTOR flowchart that has two parallel arrays: a String array named people that is initialized with the names of twenty of your friends, and a String array named phoneNumbers that is initialized with your friends’ phone numbers. The program should allow the user to enter a person’s name. It should then search for that person in the people array. If the person is found, it should get that person’s phone number from the phoneNumbers array...

  • In Java. Write a GUI contact list application. The program should allow you to input names...

    In Java. Write a GUI contact list application. The program should allow you to input names and phone numbers. You should also be able to input a name and have it display the previously entered phone number. The GUI should look something like the following, although you are welcome to format it in any way that works. This should be a GUI application with a JFrame. The program should contain two arrays of Strings. One array will contain a list...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT