You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的Python for循环出现Invalid Syntax语法错误?

解决你的Python字典程序语法错误问题

嘿,我帮你揪出代码里导致Invalid Syntax错误的几个问题啦,咱们逐个拆解修复:

具体错误点及修复方法

  • main函数代码块缺少缩进:Python是靠缩进区分代码块的,def main():之后的所有函数内代码都要缩进(推荐用4个空格),不然解释器会把它们当成函数外的独立代码,直接触发语法错误。
  • findName函数的return位置错误:你把return nameList写在for循环内部了,这样第一次循环就会直接返回结果,根本遍历不完所有联系人。得把它移到for循环外面,确保收集到所有匹配号码的名字。
  • sorted函数调用缺少括号:printAll函数里的for key in sorted contacts:是错误的,调用函数必须加括号传递参数,应该改成for key in sorted(contacts):。
  • print语句的语法错误:print(key.contacts[key])这里用点连接是错误的,应该用逗号分隔键和对应的值,改成print(key, contacts[key])才能正确打印名字和号码。
  • 可选优化:字典定义里的反斜杠\其实没必要,如果要换行写字典,直接拆成多行即可,可读性更强。

修正后的完整代码

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

内容的提问来源于stack exchange,提问作者afg229

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:06:28