gpt4 book ai didi

python - 为什么我在 for 循环中收到无效语法错误?

转载 作者:行者123 更新时间:2023-12-01 01:54:31 25 4
gpt4 key购买 nike

我正在编写一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com