为什么"else"行给出了无效的语法错误?

Mat*_*ski 18 python if-statement indentation syntax-error

我有这个错误:

File "zzz.py", line 70
    else:
       ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

导致问题的行在代码中标有注释:

def FileParse(self, table_file):
    vars={}
    tf = open(table_file, 'r')
    for line in tf:
        if line.startswith("#") or line.strip() == "": pass
        elif line.startswith("n_states:"):
            self.n_states = str(line[9:].strip())
        elif line.startswith("neighborhood:"):
            self.neighborhood = str(line[13:].strip())
        elif line.startswith("symmetries:"):
            self.symmetries = str(line[11:].strip())
        elif line.startswith("var "):
            line = line[4:]
            ent = line.replace('=',' ').\
            replace('{',' ').\
            replace(',',' ').\
            replace(':',' ').\
            replace('}',' ').\
            replace('\n','').split()
            vars[ent[0]] = []
            for e in ent[1:]:
                if e in vars: vars[ent[0]] += vars[e]
                else: 
                    vars[ent[0].append(int(e))]     
        else:
            rule = line.strip().split(",")
            for k in vars.keys():
                if k in rule:
                    for i in vars[k]:
                        change = rule.replace(k, i)
                        change = [int(x) for x in change]
                        w.rules.append(Rule(change[:5],change[5])

                else: # line which causes the problem

                    rule = [int(x) for x in rule]
                    w.rules.append(Rule(rule[:5],rule[5]))                  
    tf.close()
    self.parse_status "OK"
    return w.rules
Run Code Online (Sandbox Code Playgroud)

w.rules 是变量,分配给"世界"类.

说实话,我不知道为什么我会这样做.在一切都很好之前,现在在其他缩进块中添加一些额外的指令后出现错误.

有任何想法吗?

kur*_*umi 35

因为你遗漏了一个右大括号

w.rules.append(Rule(change[:5],change[5]) )
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是这有多少赞成.我猜这意味着很多人都有这个确切的问题 - 你会认为Python会改进它的错误信息,以便更少的人会这样做. (6认同)