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

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

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值