简体   繁体   中英

Why am i not able to modify it?

I'm new to programming and i'm struggling a bit. I'm working with python and im supposed to write an address book where I can modify a current contact but i can't do it.

Here is the coding for modifying a current contact:

    print("Here is your address book.")

ContactList = []


'''import os
import time


saveFile = open("contactlist.txt", "r")
contactString = saveFile.read()
saveFile.close()

ContactList = ContactListString.split('\n')

while '' in ContactList:
    ContactList.remove('')'''



def saveContacts():
    oFile = open("contactlist.txt", 'w')

    for contact in ContactList:
        oFile.write(contact[0] + ', ' + contact[1] + ', ' + contact[2] + '\n')
    oFile.close()
#To save information and then use it to save information during other processes.
#It's to save information about the different contacts.




def addContact():
    print("You have chosen to add a new contact into your address book.")
    name = input("What's the contacts name? ")

    counter = ContactList.count(name)
    if counter == 0:
        address = input("Enter the address of " + name + ': ')
        email = input("Enter the email of " + name + ': ')
        ContactList.append([ name, address, email ])
        saveContacts()
    else:
        print("The contact already exists in the address book.")
        print("If you desire to change the contacts current information, enter nr 3 in the menu.")
#Here we're supposed to add new contacts.
#The variables counter are there to see if the name that the person is trying to add already exist or not.'
    #This will help the person so that they won't get multiple people with the same name and information.
        #If the contact already exist you have the option to either let it stay or modify it by entering nr. 3 in the menu.




def deleteContact():
    print("You have chosen to delete a specific contact from your address book.")
    printContacts()
    number = int(input("What contact do you want to remove?"))
    ContactList.pop(number - 1)
    print("The contact and the information about them are now deleted from the adress book.")
    saveContacts()
    printContacts()
#Here is where you're supposed to delete your contact.
    #When you choose a number, everything in that line, whether you have their address and email, will get deleted.
        #Then it will save the new so called update and print all your contacts for you to view them.




def printContacts():
    index = 1
    for contact in ContactList:
        print("{}: {}".format(index, contact))
        index = index + 1
    saveContacts()
#This exist because we want to print contacts out, to view them and to sort them after an index to make it easier for us to view and choose contact.
    #It makes it easier for us to just add a number from the index instead of opening up a new file etc..




def browseContacts():
    print("You have chosen to view all  your contacts with their name, address and email.")
    print(ContactList)
#Here is where you can browse and see all your contacts and be able to view them all from your contact list.
    #You're also able to viwe their name, address and email all at once.




def searchContacts():
    print("Here you'll be able to search for people that are already in the address book.")
    criteria = input("Please enter any keywords, including name, address or email to find the contact: ")
    for line in ContactList:
        if criteria in line:
            print(line)
        else:
            print("Couldn't find that contact. Please add him/her/it to the address book first or check if your spelling was correct or not.")
#Here you're able to search up contacts that you currently have in your contact list.
    #When you search them up : you will be able to see their name, their address and their email all at once.
    #If the program doesn't find their name, address or email : it tells you to add him/her/it into your list before searching it up.



def modifyContacts():
        printContacts()
        contactToEdit = int(input("What contact do you want to edit? Choose a number."))
        Contact = contact[contactToEdit-1]

        print("If you want to edit, press 1 : ")
        print("If you dont want to edit, press 2: ")
        toEdit = input("")
        if toEdit == "1":
            Contact["name"] = input('Enter your new name: ')
            Contact["address"] = input('Enter your new address: ')
            Contact["email"] = input('Enter your new mail: ')
    #        ContactList[0] = input(' Enter the new name of the contact: ')
    #        ContactList[1] = input(' Enter the new address of ' + ContactList[0] + ': ')
    #        ContactList[2] = input(' Enter the new e-mail of ' + ContactList[0] + ': ')
        elif toEdit == "2":
            print("You can choose to do something else.")
        else:
            print("Not a valid option.")
        print()




'''
    toEdit = input("")
    if toEdit == "1":
#        ContactList.append(input(' Enter the new name of the contact: '))
#        ContactList.append(input(' Enter the new address of ' + str(ContactList[0]) + ': ')) 
#        ContactList.append(input(' Enter the new e-mail of ' + str(ContactList[0]) + ': ')) 
        contact[0] = input(' Enter the new name of the contact: ')
        contact[1] = input(' Enter the new address of ' + ContactList[0] + ': ')
        contact[2] = input(' Enter the new e-mail of ' + ContactList[0] + ': ')
    elif toEdit == "2":
        print("You can choose to do something else.")
    else:
        print("Not a valid option.")
    print()
'''




running = True
while running == True:

    print('''
-------------------------------------------------------------------
 Choose what you want to do / The menu:

 1: Add a new contact : please enter nr. 1
 2: Delete a contact : please enter nr. 2
 3: Modify a current contact : please enter nr. 3
 4: Search up a contact : please enter nr. 4
 5: Browse current contacts : please enter nr. 5
 6: Quit the program : please enter nr. 6

-------------------------------------------------------------------''')

    chooseAct = input("Please enter the number of what you desire to do: ")

    if chooseAct == '1':   
        addContact()

    elif chooseAct == '2':
        deleteContact()

    elif chooseAct == '3':
        modifyContacts()

    elif chooseAct == '4':
        searchContacts()

    elif chooseAct == '5':
        browseContacts()

    elif chooseAct == '6':
        print("Shutting down. Thank you for using the adressbook!")
        running = False

    else:
        print('\n The entered command does not exist within this program. Please enter one of the actions shown in the menu below: \n')

#Here is a menu and for the user to choose what to do, do they want to add, delete, modify, search up, browse or quit the program : it's all their choice.
    #It's easy to have a menu because it results in easy accses to whatever you desire to do.
    #It's also in a running state so you decide when you want the program to quit running.
    #The variable (chooseAct) is there as an input of a lot of strings with lots of functions to do different things.
    #There is also else : so if you click on a value which is not avaliable, you have the choice to rewrite one or quit the program, the choices you have are rewritten for you in the menu.

The code for my ContactList is this:

ContactList = []

I don't get what the problem is, when i had ContactList[0], ContactList[1] and ContactList[2], it said that the list was out of range, but where am i supposed to tell how long the list is supposed to be?

I realized that append results in me getting a completely new contact which i don't want, I want to modify a current one, so that's wrong.

But what am i supposed to do to actually modify a current contact? And how am i supposed to make the list "avaliable"?

Thank you so much!

To begin with a empty list, you will need to add one first. You can avoid the error by adding a condition before modify it. The best way to do it is to separate your code and write a dedicated function for adding contacts.

def modifyContacts():
    if not ContactList:
        addContacts()
    else:
        # your modifying code

def addContacts():
    # your adding contact code

You need to use dictionaries with lists to get optimal output!.Hope this helps

    contacts = []
    def createcontact():
        newcontact = {}
        newcontact["name"] = input('Enter your name: ')
        newcontact["address"] = input('Enter your address: ')
        newcontact["email"] =  input('Enter your mail: ')
        contacts.append(newcontact)

    def printContacts():
        for contact in range(len(contacts)):
            print(str(contact+1)+") Name:"+contacts[contact]["name"]+" Address:"+contacts[contact]["address"]+" Email:"+contacts[contact]["email"])
    def modifyContacts():
        printContacts()
        contactToEdit = int(input("What contact do you want to edit? Choose a number."))
        Contact = contacts[contactToEdit-1]

        print("If you want to edit, press 1 : ")
        print("If you dont want to edit, press 2: ")
        toEdit = input("")
        if toEdit == "1":
            Contact["name"] = input('Enter your new name: ')
            Contact["address"] = input('Enter your new address: ')
            Contact["email"] = input('Enter your new mail: ')
    #        ContactList[0] = input(' Enter the new name of the contact: ')
    #        ContactList[1] = input(' Enter the new address of ' + ContactList[0] + ': ')
    #        ContactList[2] = input(' Enter the new e-mail of ' + ContactList[0] + ': ')
        elif toEdit == "2":
            print("You can choose to do something else.")
        else:
            print("Not a valid option.")
        print()

    createcontact()
    createcontact()
    modifyContacts()
    printContacts()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM