如何处理“意外缩进"?在python中? [英] What to do with "Unexpected indent" in python?

查看:315
本文介绍了如何处理“意外缩进"?在python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何纠正python中的意外缩进"错误?

How do I rectify the error "unexpected indent" in python?

推荐答案

Python在行的开头使用空格来确定代码块的开始和结束时间.您会得到的错误是:

Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:

意外缩进.这行代码的开头比以前的空格多,但前面的空格不是子块的开头(例如if/while/for语句).块中的所有代码行必须以完全相同的空白字符串开头.例如:

Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines of code in a block must start with exactly the same string of whitespace. For instance:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent

当以交互方式运行python时,这一点尤其常见:请确保在命令前不要放置任何多余的空格. (复制和粘贴示例代码时非常烦人!)

This one is especially common when running python interactively: make sure you don't put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)

>>>   print "hello"
IndentationError: unexpected indent

非缩进不匹配任何外部缩进级别.该行的开头比以前的空格少,但同样不匹配它可能属于的任何其他块. Python无法决定它的去向.例如,在下面,最终的打印是否应该包含在if子句中?

Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?

>>> if user == "Joey":
...     print "Super secret powers enabled!"
...   print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level

期望缩进的块.该行代码的开头与前面的空格数量相同,但是最后一行有望开始一个块(例如if/while/for语句,函数定义).

Expected an indented block. This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition).

>>> def foo():
... print "Bar"
IndentationError: expected an indented block

如果您想要一个不执行任何操作的函数,请使用"no-op"命令 pass :

If you want a function that doesn't do anything, use the "no-op" command pass:

>>> def foo():
...     pass

允许混合制表符和空格(至少在我的Python版本中),但是Python假定制表符的长度为8个字符,可能与您的编辑器不匹配. 只需在标签上说否"即可.大多数编辑器允许它们自动由空格代替.

Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces.

避免这些问题的最佳方法是在缩进子块时始终使用一致数量的空格,并且理想情况下使用可以为您解决问题的良好IDE.这也将使您的代码更具可读性.

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.

这篇关于如何处理“意外缩进"?在python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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