为什么我在for循环中遇到无效的语法错误?

时间:2018-05-16 16:54:28

标签: python dictionary syntax-error

我正在编写一个python程序来显示字典的元素,但是当我运行程序时,我收到一个无效的语法错误。我在for循环中的第3行到最后一行收到错误。有谁知道为什么会出现这个错误?

def main():
    my_contacts = {"Fred":7239591, "Mary":3841212, "Bob":3841212, \
               "Sarch":2213278}
    if 'Fred' in my_contacts:
        print('Number for Fred', my_contacts["Fred"])
    else:
        print("Fred is not in my_contacts list.")
    nameList = findName(my_contacts, 3841212)
    print("Names for 3841212:", end = " ")
    for name in nameList:
        print(name, end=" ")
    print()
    printAll(my_contacts)

def findName(contacts, number):
    nameList = []
    for name in contacts:
        if contacts[name]==number:
            nameList.append(name)
    return nameList

def printAll(contacts):
    print("All names and numbers")
    for key in sorted contacts:
        print(key.contacts[key])
main()

3 个答案:

答案 0 :(得分:1)

这有效

def main():
    my_contacts = {"Fred":7239591, "Mary":3841212, "Bob":3841212, \
               "Sarch":2213278}
    if 'Fred' in my_contacts:
        print('Number for Fred', my_contacts["Fred"])
    else:
        print("Fred is not in my_contacts list.")
    nameList = findName(my_contacts, 3841212)
    print("Names for 3841212:", end = " ")
    for name in nameList:
        print(name, end=" ")
    print()
    printAll(my_contacts)

def findName(contacts, number):
    nameList = []
    for name in contacts:
        if contacts[name]==number:
            nameList.append(name)
    return nameList

def printAll(contacts):
    print("All names and numbers")
    for key in sorted(contacts):
      print(key, contacts[key])
main()

打印此输出:

Number for Fred 7239591
Names for 3841212: Mary Bob 
All names and numbers
Bob 3841212
Fred 7239591
Mary 3841212
Sarch 2213278

答案 1 :(得分:1)

您的语法不正确。将您的printAll功能更改为以下内容 -

def printAll(contacts):
    print("All names and numbers")
    for key in sorted(contacts):
        print(key, contacts[key])

答案 2 :(得分:0)

查看代码问题,用箭头键表示 -

def printAll(contacts):
    print("All names and numbers")
                -----------------
    for key in | sorted contacts: |  <-
                ````````````````` 
        print(key.contacts[key])
                 ^

尝试运行时应该抛出的错误:

for key in sorted contacts:
                         ^
SyntaxError: invalid syntax

您可以通过以下方式解决 -

def printAll(contacts):
    print("All names and numbers")
    for key in sorted(contacts):
        print(f'{key} {contacts[key]}')

代码的预期完整输出 -

Number for Fred 7239591
Names for 3841212: Mary Bob 
All names and numbers
Bob 3841212
Fred 7239591
Mary 3841212
Sarch 2213278