我正在编写一个 python 程序来显示字典的元素,但是当我运行该程序时,我收到了无效语法错误。我在 for 循环的第三行到最后一行收到错误。有谁知道为什么会出现这个错误?
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()
最佳答案
您的语法不正确。更改您的 printAll
函数,如下所示 -
def printAll(contacts):
print("All names and numbers")
for key in sorted(contacts):
print(key, contacts[key])
关于python - 为什么我在 for 循环中收到无效语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50376287/