我的.index()代码中的python代码语法错误

时间:2015-12-03 19:24:35

标签: python syntax

我正在做这个家庭作业问题,其中这段代码是从用户这样的名字或电话中检索搜索输入,它将从代码中的列表中打印出信息。我不知道 我在第一次出现变量“place”的地方不断收到语法错误

place = int(name.index(search))

老实说,我不知道为什么会这样,可能只是我对使用这些功能的无知

contact = [["John","Steve","Jane", "Sally","Pam"],["999-555-1122","999-444-2233", "999-333-3344","999-222-4455", "999-111-5566"],["john@itp.com","steve@itp.com","jane@itp.com","sally@itp.com","pam@itp.com"]]
name    = contact[0]
phone   = contact[1]    
email   = contact[2]
n=0
while n == 0:
    command = str(input("Choose command (list,name,number,email,add,remove,quit):"))
    if   command == ("list"):
        print (contact)
    elif command == ("name"):
        search = str(input("Input name:")
        place= int(name.index(search))
        if search in name:
            print("Contact Found")
            print (name[place])
            print (phone[place])
            print (email[place])
        else:
            print("Contact could not be found")
    elif command == ("number"):
        search = str(input("Input name:")
        place  = int(name.index(search))
        if search in name:
            print("Contact Found")
            print (name[place])
            print (phone[place])
        else:
            print("Contact could not be found")

    elif command == ("email"):
        search = str(input("Input name:")
        place  = int(name.index(search))
        if search in name:
            print("Contact Found")
            print (name[place])
            print (email[place])
        else:
            print("Contact could not be found")
    elif command == ("add"):
        print ("Adding New Contact:")
        newname  = str(input("Name :"))
        newphone = str(input("Phone:"))
        newemail = str(input("Email:"))
        name.append(newname)
        phone.append(newphone)
        email.append(newemail)
    elif command == ("remove"):
        contactdel= str(input("Which contact information would you like to remove?"))
        if contactdel in name:
            confirm = str(input("Are you sure you want to delete this contact?(y or n)"))
            if confirm == ("y"):
                contactfind=name.index(contactdel)
                name.pop([contactfind])
                phone.pop([contactfind])
                email.pop([contactfind])
                print ("Contact has been sucessfully deleted")
            elif confirm == ("n"):
                print ("Contact will not be deleted")
            else:
                print ("ERROR.....INPROPER INPUT.....ERROR")

    elif command == ("quit"):
        n = 1

1 个答案:

答案 0 :(得分:1)

语法错误通常比代码高出python最终意识到出错的点。在您的情况下,查找一行

search = str(input("Input name:")

最后错过了最后的结局。

当我在发现语法错误时遇到问题时,我只将一小部分有问题的代码粘贴到一个单独的文件中并从那里开始。例如,这个脚本会产生同样的问题,并且更容易发现问题

search = str(input("Input name:")
place  = int(name.index(search))