<p>实际上,关于Python中的缩进,您需要了解的内容有很多:</p>
<h2><strong>Python非常关心缩进。</strong></h2>
<p>在许多其他语言中,缩进是不必要的,但可以提高可读性。在Python中,缩进替换关键字<code>begin / end</code>或<code>{ }</code>,因此是必要的。</p>
<p>这是在代码执行之前验证的,因此即使永远无法到达带有缩进错误的代码,它也不会工作。</p>
<h2><strong>有不同的缩进错误,阅读这些错误会有很大帮助:</strong></h2>
<p><strong>1缩进错误:需要缩进的块“</strong></p>
<p>有两个主要原因会导致您出现这样的错误:</p>
<p><strong>-您有一个“:”后面没有缩进的块。</strong></p>
<p>下面是两个例子:</p>
<p><strong><em>示例1,无缩进块:</em></strong></p>
<p>输入:</p>
<pre><code>if 3 != 4:
print("usual")
else:
</code></pre>
<p>输出:</p>
<pre><code> File "<stdin>", line 4
^
IndentationError: expected an indented block
</code></pre>
<p>输出声明您需要在第4行的<code>else:</code>语句之后有一个缩进块</p>
<p><strong><em>示例2,未缩进块:</em></strong></p>
<p>输入:</p>
<pre><code>if 3 != 4:
print("usual")
</code></pre>
<p>输出</p>
<pre><code> File "<stdin>", line 2
print("usual")
^
IndentationError: expected an indented block
</code></pre>
<p>输出声明需要在<code>if 3 != 4:</code>语句之后有一个缩进的块行2</p>
<p><strong>-您使用的是Python2.x,它混合了制表符和空格:</strong></p>
<p>输入</p>
<pre><code>def foo():
if 1:
print 1
</code></pre>
<p>请注意,如果之前有制表符,打印之前有8个空格。</p>
<p>输出:</p>
<pre><code> File "<stdin>", line 3
print 1
^
IndentationError: expected an indented block
</code></pre>
<p>很难理解这里发生了什么,似乎有一个缩进块。。。但正如我所说,我使用了标签和空格,你不应该这样做。</p>
<ul>
<li>你可以得到一些信息。</li>
<li>删除所有选项卡并用四个空格替换它们。</li>
<li>并将编辑器配置为自动执行此操作。</li>
</ul>
<p><strong>2缩进错误:意外缩进“</strong></p>
<p>缩进块很重要,但只缩进应该缩进的块。
所以基本上这个错误说:</p>
<p><strong>-前面有一个没有“:”的缩进块。</strong></p>
<p><strong><em>示例:</em></strong></p>
<p>输入:</p>
<pre><code>a = 3
a += 3
</code></pre>
<p>输出:</p>
<pre><code> File "<stdin>", line 2
a += 3
^
IndentationError: unexpected indent
</code></pre>
<p>输出表明他不需要缩进块行2,然后应该将其删除。</p>
<p><strong>3。”TabError:缩进“</strong>中不一致地使用制表符和空格(仅限python3.x)</p>
<ul>
<li>你可以得到一些信息。</li>
<li>但基本上,您在代码中使用了制表符和空格。</li>
<li>你不想那样。</li>
<li>删除所有选项卡并用四个空格替换它们。</li>
<li>并将编辑器配置为自动执行此操作。</li>
</ul>
<p/><hr/>
最后,回到你的问题上来:
<p>只需查看错误的行号,然后使用前面的信息修复它。</p>