了解Python 2.7中的IndentationErrors [英] Understanding IndentationErrors in Python 2.7

查看:54
本文介绍了了解Python 2.7中的IndentationErrors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写python代码时,我倾向于得到很多IndentationErrors.有时,当我删除并重写该行时,错误就会消失.有人可以为noob提供python中的IndentationErrors的高级解释吗?

I tend to get a LOT of IndentationErrors when writing python code. Sometimes the error will go away when I delete and rewrite the line. Can someone provide a high level explanation of IndentationErrors in python for noob?

以下是我在玩CheckIO时收到的最近的indentationError的示例,该错误不会消失:

Here is an example of a recent indentationError I received while playing CheckIO that will not go away:

def checkpass(data):
     """Checks password for >=10 char + 1 number + 1 LC letter + 1 UC letter"""

     passlist = []
     uclist = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
               'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 
               'Y', 'Z']
     lclist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
               'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
               'y', 'z']

     blah blah.. more code

这是我调用python脚本时收到的错误:

Here is the error that I receive when I call the python script:

$ python passcheck.py
File "passcheck.py", line 5
uclist = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                                                                    ^
IndentationError: unindent does not match any outer indentation level

推荐答案

当您混合使用制表符和空格时,通常会出现这种问题.

This kind of issues usually arise when you mix tabs and spaces.

某些编辑器可能会将 Tab 显示为4个空格,但是在Python 2.x中, Tab 被解释为8个空格,因此即使编辑器显示多行缩进了在同一级别,对于python来说,它们可能实际上并没有在同一级别缩进(特别是如果编辑器将制表符解释为4个空格)

Some editors may show Tab as 4 spaces, but in Python 2.x Tab is interpreted as 8 spaces, so even though the editor shows that multiple lines are indented at the same level, they may not really be indented at the same level for python (Especially if the editor interprets the tab as 4 spaces)

在Python 3.x中,根本不允许混用制表符和空格,这将引发在同一python脚本中混用制表符和空格的语法错误.

In Python 3.x , you are not allowed to mix tabs and spaces at all, it would throw a syntax error for mixing tabs and spaces in the same python script.

理想情况下,您应该在脚本中使用完全制表符或完全使用空格,建议缩进使用4个空格.

Ideally, you should either use completely tabs or completely spaces throughout your script , 4 spaces is the recommended practice for indentation.

这篇关于了解Python 2.7中的IndentationErrors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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