Python elif 中的无效语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21277385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:27:47  来源:igfitidea点击:

Python Invalid syntax in elif

pythonif-statementsyntax-error

提问by abhisekG

The code below shows in invlid syntax in the first elif statement. I have checked and rechecked my code several times, but cant figure out how to solve the error.

下面的代码在第一个 elif 语句中以 invlid 语法显示。我已经多次检查并重新检查了我的代码,但无法弄清楚如何解决错误。

fileHandle = open ( 'gra1.txt' )
count=0
count1=0
fileList = fileHandle.readlines()
for fileLine in fileList:
    line=fileLine.split()
    if line[0] == '0':
        print "graph G%d {\n", (count)
        count +=1
    elif line[0] == '1':
        print "} \n"
    elif line[0]=='':
        continue
    else:
        count1 += 1
        if count1==1: a=line[0]
        elif count1==2: relation=line[0]
        elif count1==3: b=line[0]
        else:
            print a, relation, b
            count1=0
fileHandle.close()

采纳答案by gravetii

Your elifis not indented properly...it should be indented the same way ifis indented. Seeing the elseblock, it seems that you have by mistake indented the first if. Remember that elif/elseshould be preceded by an ifalways.

elif没有正确缩进……它应该以与缩进相同的方式if缩进。看到else块,您似乎错误地缩进了第一个if. 请记住,elif/else前面应该有一个ifalways。

EDIT:corresponding to the edited question details: Why is the second elsethere? It isn't preceded by an if. I feel you need to get your conditions organized properly before writing the code.

编辑:对应于编辑的问题详细信息:为什么第二个else在那里?它前面没有if. 我觉得你需要在编写代码之前正确组织你的条件。

One way to correct the code is to change this to an elifblock:

更正代码的一种方法是将其更改为elif块:

else:
    count1 += 1
    if count1==1: a=line[0]
    elif count1==2: relation=line[0]
    elif count1==3: b=line[0]

You might want your indentation in Python to get better. Consider reading up a bit on that :-)

您可能希望 Python 中的缩进变得更好。考虑阅读一下:-)

回答by madprogramer

if line[0] == '0':
    print "graph G%d {\n", (count)
    count +=1
elif line[0] == '1':

It seems that you accidentally missplaced your first elif. In that state it matches no if's so you get an error.

您似乎不小心放错了第一个 elif。在那种状态下它不匹配 if,所以你会得到一个错误。