当前位置:   article > 正文

解决IndentationError:unindent与任何外部缩进级别都不匹配

unindent does not match any outer indentation

Majority of the time new Python developers face one common problem and that is of IndentationError: unindent does not match any outer indentation level and they are not able to figure out why this error occurred.

大多数时候,新的Python开发人员都面临一个常见的问题,那就是IndentationError:unindent与任何外部缩进级别都不匹配,并且他们无法弄清楚为什么会发生此错误。

In this post, I’ll be discussing some of the ways to overcome IndentationError. But before getting started, I’d like to tell you guys that Python is very strict about Indentation and if any of your code blocks is not indented, the interpreter is going to complain about the indentation.

在本文中,我将讨论一些克服IndentationError的方法。 但是在开始之前,我想告诉大家Python对缩进非常严格,如果您的任何代码块都未缩进,则解释器将抱怨缩进。

Let us see this with an example.

让我们看一个例子。

print("Hello, World!")

Here, you can see that the code has an extra space in front of it and when you’ll try to run your python file, this will throw an error.

在这里,您可以看到代码前面有一个额外的空间,当您尝试运行python文件时,这将引发错误。

如何解决错误? (How to Solve the Error?)

停止使用空格 (Stop Using spaces)

The best way to avoid these kinds of error is to stop using spaces for indentation and start using tabs for indentation.

避免此类错误的最佳方法是停止使用空格进行缩进,而开始使用制表符进行缩进。

When you mix spaces with tabs in your code, then the compiler throws an indentation error.

当您在代码中将空格与制表符混合时,编译器将引发缩进错误。

标签的使用 (Use of Tabs)

Use tabs in place of spaces and this will remove all the indentation error your python code may have. This maintains consistency which reduces the chance of indentation error in your code. Using spaces may lead to some extra space but tabs are of fixed width. It will always give you either 2 space or 4 space depending upon your editor’s configuration.

使用制表符代替空格,这将消除您的python代码可能存在的所有缩进错误。 这样可以保持一致性,从而减少代码中出现缩进错误的可能性。 使用空格可能会导致一些额外的空间,但是制表符的宽度是固定的。 根据编辑器的配置,它将始终为您提供2个空间或4个空间。

使用代码格式化程序 (Using Code Formatter)

One another way to get rid of indentation error is to use some code formatter.  This will help you to format your code properly and will help you to format code blocks which are not properly formatted.

消除缩进错误的另一种方法是使用某些代码格式化程序。 这将帮助您正确设置代码格式,并帮助您格式化未正确设置格式的代码块。

I hope this will solve the error. Still if you have any queries ask in the comment section.

我希望这可以解决错误。 不过,如果您有任何疑问,请在评论部分中询问。

翻译自: https://www.thecrazyprogrammer.com/2020/08/unindent-does-not-match-any-outer-indentation-level.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/168242
推荐阅读
相关标签
  

闽ICP备14008679号