为什么我无法修改它?

时间:2018-12-04 18:49:44

标签: python

我是编程新手,但我有点挣扎。 我正在使用python,我应该写一个通讯录,在这里我可以修改当前联系人,但我做不到。

这是修改当前联系人的代码:

    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.

我的ContactList的代码是这样的:

ContactList = []

我不明白问题是什么,当我有ContactList [0],ContactList [1]和ContactList [2]时,它说列表不在范围内,但是我应该在哪里告诉我多长时间该列表应该是吗?

我意识到,追加会导致我得到一个我不想要的全新联系人,我想修改当前联系人,所以这是错误的。

但是我应该怎么做才能真正修改当前联系人? 我应该如何使列表“可用”?

非常感谢您!

2 个答案:

答案 0 :(得分:0)

要从一个空列表开始,您需要先添加一个。您可以通过在修改条件之前添加条件来避免错误。最好的方法是分离代码并编写用于添加联系人的专用功能。

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

def addContacts():
    # your adding contact code

答案 1 :(得分:0)

您需要将字典与列表结合使用才能获得最佳输出!希望如此

    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()