Python中的意外缩进错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4263485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:59:02  来源:igfitidea点击:

Unexpected Indent error in Python

python

提问by tjsimmons

I have a simple piece of code that I'm not understanding where my error is coming from. The parser is barking at me with an Unexpected Indent on line 5 (the if statement). Does anyone see the problem here? I don't.

我有一段简单的代码,我不明白我的错误来自哪里。解析器在第 5 行(if 语句)用意外的缩进对我咆哮。有没有人看到这里的问题?我不。

def gen_fibs():
    a, b = 0, 1
    while True:
        a, b = b, a + b
        if len(str(a)) == 1000:
            return a

采纳答案by aaronasterling

If you just copy+pasted your code, then you used a tab on the line with the ifstatement. Python interprets a tab as 8 spaces and not 4. Don't ever use tabs with python1:)

如果您只是复制+粘贴代码,那么您在if语句行上使用了制表符。Python 将制表符解释为 8 个空格而不是 4 个。不要在 Python 1 中使用制表符:)

1 Or at least don't ever use tabs and spaces mixed. It's highly advisable to use 4 spaces for consistency with the rest of the python universe.

1 或者至少不要混合使用制表符和空格。强烈建议使用 4 个空格以与 python 世界的其余部分保持一致。

回答by Marek Sapota

Check if you aren't mixing tabs with spaces or something, because your code pasted verbatim doesn't produce any errors.

检查您是否没有将制表符与空格或其他东西混合在一起,因为逐字粘贴的代码不会产生任何错误。

回答by luqui

The line with a, b = b, a + bis indented with 8 spaces, and the ifline is indented with 4 spaces and a tab. Configure your editor to never ever insert tabs ever.

with 行a, b = b, a + b缩进 8 个空格,该if行缩进 4 个空格和一个制表符。将您的编辑器配置为永远不要插入标签。

(Python considers a tab to be 8 spaces, but it's easier just not to use them)

(Python 认为制表符为 8 个空格,但不使用它们更容易)

回答by Ignacio Vazquez-Abrams

You're mixing tabs and spaces. Tabs are alwaysconsidered the same as 8 spaces for the purposes of indenting. Run the script with python -ttto verify.

您正在混合制表符和空格。出于缩进的目的,制表符始终被视为与 8 个空格相同。运行脚本以python -tt进行验证。

回答by icyrock.com

Check whether your whitespace in front of every line is correctly typed. You may have typed tabs instead of spaces - try deleting all the space and change it so you use only tabs or only spaces.

检查每行前面的空格是否正确键入。您可能输入了制表符而不是空格 - 尝试删除所有空格并进行更改,以便仅使用制表符或仅使用空格。