Python if/elif 语法错误...为什么
Python if/elif syntax error... WHY
我对此非常紧张。此函数中的 if/elif 语句在 elif 行上抛出语法错误。对我来说没有明显的语法问题。
"elif n == cs_index:"
^
SyntaxError: invalid syntax
我试着把它换成熊 "else:" 只是想看看它是否会愚蠢地表达出来,但事实并非如此。我确定有一些我没有看到的东西。
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")
将我的代码粘贴到我的 Spyder IDE 和 运行 之后,我没有出现任何错误(除了 print
语句中缺少的括号 - 你真的应该升级到 Python 3.5.2!)
尝试通过重置缩进并添加三个制表符来重新缩进该行。当我复制和粘贴使用空格缩进的代码时,我遇到了类似的错误。
您在代码中混用了制表符和空格;获取初始 post 的来源并将其粘贴到 Sublime Text 中,然后选择我看到的所有行:
灰线是制表符,点是空格。我将选项卡设置为每 4 列展开一次,您可能有相同的设置。
Python,将选项卡扩展到每个 8th 列,看到这个:
请注意 elif
缩进 如何匹配前面的行 ,因为这 4 个空格后面的制表符被扩展到 第一个 [=37] =] 第 8 列,不是第二列。这就是您看到的异常的原因。
不要混用制表符和空格。最好坚持缩进空格 only;这就是 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 键,但是您的编辑器会在您这样做时使用空格来缩进行。
我对此非常紧张。此函数中的 if/elif 语句在 elif 行上抛出语法错误。对我来说没有明显的语法问题。
"elif n == cs_index:"
^
SyntaxError: invalid syntax
我试着把它换成熊 "else:" 只是想看看它是否会愚蠢地表达出来,但事实并非如此。我确定有一些我没有看到的东西。
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")
将我的代码粘贴到我的 Spyder IDE 和 运行 之后,我没有出现任何错误(除了 print
语句中缺少的括号 - 你真的应该升级到 Python 3.5.2!)
尝试通过重置缩进并添加三个制表符来重新缩进该行。当我复制和粘贴使用空格缩进的代码时,我遇到了类似的错误。
您在代码中混用了制表符和空格;获取初始 post 的来源并将其粘贴到 Sublime Text 中,然后选择我看到的所有行:
灰线是制表符,点是空格。我将选项卡设置为每 4 列展开一次,您可能有相同的设置。
Python,将选项卡扩展到每个 8th 列,看到这个:
请注意 elif
缩进 如何匹配前面的行 ,因为这 4 个空格后面的制表符被扩展到 第一个 [=37] =] 第 8 列,不是第二列。这就是您看到的异常的原因。
不要混用制表符和空格。最好坚持缩进空格 only;这就是 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 键,但是您的编辑器会在您这样做时使用空格来缩进行。