简体   繁体   English

为什么这会引起缩进错误?

[英]why does this throw indentation error?

for bucketLabel, eventList in test_source_json.iteritems(): 
    if bucketLabel == "spotlight": 
        for event in eventList: 
            try: 
                for key in source_keys: 
                    if key not in event: 
                        if key not in responseDictionary[currentTestName][url]: 
                            responseDictionary[currentTestName][url][key] = list()
                        responseDictionary[currentTestName][url][key].append(event)
            except: 
                exc_type, exc_obj, exc_tb = sys.exc_info()
                logging.info("caught exception %s, and obj %s at line number %s" % (exc_type, exc_obj, exc_tb.tb_lineno))
                continue    

This code throws an indentation error at line 4 try: http://repl.it/N7W illustrates the error 此代码在第4行引发缩进错误try: http try: //repl.it/N7W说明了错误

Totally confused as to why. 完全混淆为什么。

你在那条线上使用制表符而不是空格

The problem—as it often is in cases like this—is that you're mixing tabs and spaces. 问题 - 就像在这种情况下经常出现的那样 - 是你混合标签和空格。

Lines 2 and 3 are indented with tabs; 第2行和第3行用标签缩进; line 3 starts with two tab characters. 第3行以两个制表符开头。 That presumably looks like 8 spaces in your text editor, but as far as Python is concerned, it's 16 spaces. 大概在文本编辑器中看起来像8个空格,但就Python而言,它是16个空格。

Line 4 is indented with 12 spaces. 第4行缩进12个空格。 So, in your editor, it looks more indented than line 3. But to Python, it's less indented. 所以,在你的编辑器中,它看起来比第3行更缩进。但是对于Python来说,它的缩进程度较低 Hence the error. 因此错误。

The solution is to always use spaces, never tabs. 解决方案是始终使用空格,而不是标签。 (Alternatively, you can always use tabs instead, just so long as you don't mix them… but always spaces is easier and better in many ways.) (或者,您可以随时使用制表符,只要您不混合它们......但在许多方面,空格总是更容易和更好。)

Most editors can be configured to do this—and to show tabs distinctly differently from spaces. 大多数编辑器都可以配置为执行此操作,并显示与空格明显不同的选项卡。 The ones that can't (like Notepad) probably shouldn't be used for programming. 那些不能(如记事本)可能不应该用于编程。

You should also run Python with the -t or -tt flag to diagnose IndentationError s, because it will tell you that you're using tabs and spaces inconsistently. 您还应该使用-t-tt标志运行Python来诊断IndentationError ,因为它会告诉您使用制表符和空格不一致。 The tabnanny module/script can also be helpful. tabnanny模块/脚本也很有帮助。

Python requires that you use either tabs or spaces for indentation and not both. Python要求您使用制表符或空格来缩进,而不是两者都使用。 The official Python recommendation is to use four spaces rather than a tab, but what's more important is you must use the same on each line. 官方Python建议使用四个空格而不是制表符,但更重要的是你必须在每一行使用相同的空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM