Python if/elif 语法错误...为什么 [英] Python if/elif syntax error... WHY

查看:55
本文介绍了Python if/elif 语法错误...为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绝对要为此而烦恼.此函数中的 if/elif 语句在 elif 行引发语法错误.对我来说没有明显的语法问题.

I'm absolutely pulling my hair out over this. The if/elif statement in this function throws a syntax error on the elif line. To me there are no obvious syntax problems.

"elif n == cs_index:"
    ^
SyntaxError: invalid syntax

我试着把它改成熊else:"只是想看看这是否会愚蠢地表达出来,但事实并非如此.我确定有些东西我没有看到.

I tried switching it to a bear "else:" just to see if that would stupidly word and it didn't. I'm sure there's something I don't see.

def higherhighlight(cs_index):
    text.tag_remove("the hello","1.0", END)
    idex = "1.0"
    for n in range(cs_index):
        if n < cs_index:
            idex = text.search("Hello", idex, nocase=1, stopindex=END)
            lastidex = idex+"+"+str(len("hello"))+"c"
            idex = lastidex
        elif n == cs_index:
            idex = text.search("Hello", idex, nocase=1, stopindex=END)
            print idex
            lastidex = idex+"+"+str(len("hello"))+"c"
            print lastidex
            text.tag_remove("hellos", idex, lastidex)
            text.tag_add("the hello", idex, lastidex)
    text.tag_config("the hello", background="dark green")

推荐答案

您在代码中混合使用制表符和空格;获取您初始帖子的来源并将其粘贴到 Sublime Text 中,然后选择我看到的所有行:

You are mixing tabs and spaces in your code; taking the source of your initial post and pasting it into Sublime Text, then selecting all lines I see this:

灰线是制表符,点是空格.我将选项卡设置为每 4 列扩展一次,您可能也有相同的设置.

The grey lines are tabs, the dots are spaces. I have tabs set to expand to every 4th column, you probably have the same setting.

Python 将选项卡扩展到每个 8th 列,看到这一点:

Python, which expands tabs to every 8th column, sees this:

注意elif如何缩进匹配前面的行,因为这4个空格后面的制表符被扩展到第一第8列,没有一秒钟.这就是您看到的异常的原因.

Note how the elif indentation matches the preceding lines, because the tab character following those 4 spaces is expanded to the first 8th column, not a second. This is the cause of the exception you see.

不要混用制表符和空格.最好坚持使用空格作为缩进only;这是 Python 样式指南推荐的内容:

Don't mix tabs and spaces. Preferably, stick to spaces for indentation only; it is what the Python styleguide recommends:

空格是首选的缩进方法.

Spaces are the preferred indentation method.

制表符应仅用于与已使用制表符缩进的代码保持一致.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

将您的编辑器配置为使用空格.您仍然可以使用 TAB 键,但您的编辑器会在您使用时使用空格来缩进行.

Configure your editor to use spaces only. You can still use the TAB key, but your editor will use spaces to indent lines when you do.

这篇关于Python if/elif 语法错误...为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆