Python:“缩进错误:取消缩进与任何外部缩进级别不匹配”

发布于 2024-08-10 23:07:20 字数 4194 浏览 2 评论 0原文

我只是不明白这有什么问题......

#!/usr/bin/env python
#
#       Bugs.py
#       

from __future__ import division

# No Module!
if __name__ != '__main__': 
    print "Bugs.py is not meant to be a module"
    exit()

# App
import pygame, sys, random, math
pygame.init()

# Configuration Vars
conf = {
    "start_energy": 50, 
    "food_energy": 25, 
    "mate_minenergy": 50, 
    "mate_useenergy": 35, 
    "lifespan": 300000
}

class Bugs:
    def __init__(self):
        self.list  = []
        self.timers= {}
        # Names / colors for sexes
        self.sex = ["Male", "Female"]
        self.color = ["#CBCB25", "#A52A2A"]
        # Bug info tracking
        self.bugid = 0
        self.buginfo = {"maxgen":0, "maxspeed":0}

    def new(self, x=False, y=False, sex=2, speed=0, generation=0, genes=[]):
        sex   = sex   if not sex   == 2 else random.randint(0,1)
        speed = speed if not speed == 0 else random.randint(1,3)
        # Create new bug object
        self.bugs.append(BugObj(sex, speed, generation, bugid, pygame.time.get_ticks, genes))
        # Make sure it has a timer
        if not self.timers[speed]:
            self.timers[speed] = 1
            pygame.time.set_timer(25 + speed, 1000 / speed)
        # Update info tracking variables
        if speed      > self.buginfo["maxspeed"]: self.buginfo["maxspeed"] = speed
        if generation > self.buginfo["maxgen"]  : self.buginfo["maxgen"]   = generation
        self.bugid += 1

    def speed_count(self, speed):
        a = 0
        for i in list[:]:
            if i.speed = speed:
                a += 1
        return a

class BugObj:
    def __init__(self, sex, speed, generation, bugid, born, genes):
        global conf
        self.sex        = sex
        self.speed      = speed
        self.generation = generation
        self.id         = bugid
        self.born       = born
        self.genes      = genes
        self.died       = -1
        self.energy     = conf["start_energy"]
        self.target     = "None"

    def update(self):
        global conf
        if self.age() > conf["lifespan"]:
            self.die()
        else:
            f = closest_food()
            m = closest_mate()
            # If there's a potential mate
            if m != 0 and self.energy > conf["mate_minenergy"]:
                if not self.rect.colliderect(m.rect):
                    self.move_toward(m)
                    self.target = "Mate: " + str(m.rect.center)
                else:
                    Bugs.mate(self, m)
                    self.target = "Mate: (Reached)"
            elif f != 0:
                if not self.rect.colliderect(f.rect):
                    self.move_toward(f)
                    self.target = "Food: " + str(f.rect.center)
                else:
                    self.eat(f)
                    self.target = "Food: (Reached)"
            else:
                self.target = "Resting"
            # Use energy
            self.energy -= 0

    def closest_food(self):
        pass

    def closest_mate(self):
        pass

    def age(self):
        if self.died != -1:
            return pygame.time.get_ticks - self.born
        else:
            return self.died - self.born

    def die(self):
        # Remove self from the list
        Bugs.list.remove(self)
        # Turn off timer
        if not Bugs.speed_count(self.speed):
            Bugs.timers[self.speed] = 0
            pygame.time.timers(25 + self.speed, 0)
        # Bye!
        del self

class Food:
    def __init__(self)
        pass

    def update(self)
        pass

# Update Loop
while 1:
    ev = pygame.event.wait()
    speed = ev.type - 25
    if speed > 24:
        for i in Bugs.list[:]:
            if i.speed = speed
                i.update()
                print "Updating bug #" + str(i.id)
    if speed == 0:
        Food.update()

我每次都会得到以下信息:

  File "Bugs.py" line 53
    def new(self, x=False, y=False, sex=2, speed=0, generation=0, genes=[]):
                                                                           ^
Indentation Error: unindent does not match any outer indentation level

I just can't figure out what's wrong with this...

#!/usr/bin/env python
#
#       Bugs.py
#       

from __future__ import division

# No Module!
if __name__ != '__main__': 
    print "Bugs.py is not meant to be a module"
    exit()

# App
import pygame, sys, random, math
pygame.init()

# Configuration Vars
conf = {
    "start_energy": 50, 
    "food_energy": 25, 
    "mate_minenergy": 50, 
    "mate_useenergy": 35, 
    "lifespan": 300000
}

class Bugs:
    def __init__(self):
        self.list  = []
        self.timers= {}
        # Names / colors for sexes
        self.sex = ["Male", "Female"]
        self.color = ["#CBCB25", "#A52A2A"]
        # Bug info tracking
        self.bugid = 0
        self.buginfo = {"maxgen":0, "maxspeed":0}

    def new(self, x=False, y=False, sex=2, speed=0, generation=0, genes=[]):
        sex   = sex   if not sex   == 2 else random.randint(0,1)
        speed = speed if not speed == 0 else random.randint(1,3)
        # Create new bug object
        self.bugs.append(BugObj(sex, speed, generation, bugid, pygame.time.get_ticks, genes))
        # Make sure it has a timer
        if not self.timers[speed]:
            self.timers[speed] = 1
            pygame.time.set_timer(25 + speed, 1000 / speed)
        # Update info tracking variables
        if speed      > self.buginfo["maxspeed"]: self.buginfo["maxspeed"] = speed
        if generation > self.buginfo["maxgen"]  : self.buginfo["maxgen"]   = generation
        self.bugid += 1

    def speed_count(self, speed):
        a = 0
        for i in list[:]:
            if i.speed = speed:
                a += 1
        return a

class BugObj:
    def __init__(self, sex, speed, generation, bugid, born, genes):
        global conf
        self.sex        = sex
        self.speed      = speed
        self.generation = generation
        self.id         = bugid
        self.born       = born
        self.genes      = genes
        self.died       = -1
        self.energy     = conf["start_energy"]
        self.target     = "None"

    def update(self):
        global conf
        if self.age() > conf["lifespan"]:
            self.die()
        else:
            f = closest_food()
            m = closest_mate()
            # If there's a potential mate
            if m != 0 and self.energy > conf["mate_minenergy"]:
                if not self.rect.colliderect(m.rect):
                    self.move_toward(m)
                    self.target = "Mate: " + str(m.rect.center)
                else:
                    Bugs.mate(self, m)
                    self.target = "Mate: (Reached)"
            elif f != 0:
                if not self.rect.colliderect(f.rect):
                    self.move_toward(f)
                    self.target = "Food: " + str(f.rect.center)
                else:
                    self.eat(f)
                    self.target = "Food: (Reached)"
            else:
                self.target = "Resting"
            # Use energy
            self.energy -= 0

    def closest_food(self):
        pass

    def closest_mate(self):
        pass

    def age(self):
        if self.died != -1:
            return pygame.time.get_ticks - self.born
        else:
            return self.died - self.born

    def die(self):
        # Remove self from the list
        Bugs.list.remove(self)
        # Turn off timer
        if not Bugs.speed_count(self.speed):
            Bugs.timers[self.speed] = 0
            pygame.time.timers(25 + self.speed, 0)
        # Bye!
        del self

class Food:
    def __init__(self)
        pass

    def update(self)
        pass

# Update Loop
while 1:
    ev = pygame.event.wait()
    speed = ev.type - 25
    if speed > 24:
        for i in Bugs.list[:]:
            if i.speed = speed
                i.update()
                print "Updating bug #" + str(i.id)
    if speed == 0:
        Food.update()

I get the following every time:

  File "Bugs.py" line 53
    def new(self, x=False, y=False, sex=2, speed=0, generation=0, genes=[]):
                                                                           ^
Indentation Error: unindent does not match any outer indentation level

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

楠木可依 2024-08-17 23:07:21

您的文件中可能混合了制表符和空格。您可以让 python 帮助检查此类错误

python -m tabnanny <name of python file>

It's possible that you have mixed tabs and spaces in your file. You can have python help check for such errors with

python -m tabnanny <name of python file>
A君 2024-08-17 23:07:21

我在使用 PyCharm 时也遇到了这个问题。我进入代码菜单并选择重新格式化代码。问题消失了。

I had this problem with PyCharm as well. I went up to the code menu and selected reformat code. Problem went away.

这个俗人 2024-08-17 23:07:21

您的原始源文件中可能混合有空格和制表符。将所有选项卡替换为四个空格(反之亦然),您应该立即看到问题。

您粘贴到问题中的代码没有这个问题,但我猜您的编辑器(或您的网络浏览器,或 Stack Overflow 本身...)可能在您不知情的情况下完成了制表符到空格的转换。

You probably have a mixture of spaces and tabs in your original source file. Replace all the tabs with four spaces (or vice versa) and you should see the problem straight away.

Your code as pasted into your question doesn't have this problem, but I guess your editor (or your web browser, or Stack Overflow itself...) could have done the tabs-to-spaces conversion without your knowledge.

以酷 2024-08-17 23:07:21

不要忘记使用“””注释。这些注释也需要精确的缩进(解决这个该死的错误对我来说也是 1/2 小时的工作!)

Don't forget the use of """ comments. These need precise indentation too (a 1/2 hr job for me resolving this damn error too!)

横笛休吹塞上声 2024-08-17 23:07:21

如果您是 VSCode 用户,那么您可能已选中 Insert Spaces 选项。这会将您按下的每个选项卡替换为空格,从而导致此问题。取消选中它就可以了。

If you're VSCode user, then you probably have Insert Spaces option checked. This will replace every tab you press by spaces which leads to this issue. Uncheck it and you're good to go.

雪落纷纷 2024-08-17 23:07:21

我使用的是 Ubuntu 11.10 附带的 gedit 基本版本。
我有同样的错误。
这主要是当您将空格与制表符混合使用时引起的。

区分哪些线路有问题的一个好方法是转到:
1. 编辑
2. 偏好
3.编辑器
4.勾选“自动缩进”
5. 执行第五步后,将缩进增加到 12 或某个大数字,

将能够看到代码中真正引起问题的行(这些行混合有空格和制表符)

您 约定只是 TAB 或空格(这必须逐行手动完成)

希望这会有所帮助...

I am using gedit basic version that comes with Ubuntu 11.10.
I had the same error.
This is mainly caused when you mix spaces with tabs.

A good way to differentiate as to which lines have problem would be to go to:
1. edit
2. preferences
3. editor
4. check "automatic indentation"
5. increase the indentation to 12 or some big number

after doing the fifth step you will be able to see the lines of your code that are relly causing problem (these are the lines that have a mix of space and tab)

Make the entire code convention as just TAB or just SPACE (this has to be done manually line by line)

Hope this helps...

清音悠歌 2024-08-17 23:07:21

IDLE 到 VISUAL STUDIO 用户:在将代码直接从 IDLE 移动到 Visual Studio 时,我也遇到了这个问题。当您按 Tab IDLE 时,会添加 4 个空格而不是制表符。在 IDLE 中,按 Ctl+A 选择所有代码并转到 Format>Tabify Region。现在将代码移至 Visual Studio,大多数错误都应该得到修复。每隔一段时间就会出现不可用的代码,只需手动修复即可。

IDLE TO VISUAL STUDIO USERS: I ran into this problem as well when moving code directly from IDLE to Visual Studio. When you press tab IDLE adds 4 spaces instead of a tab. In IDLE, hit Ctl+A to select all of the code and go to Format>Tabify Region. Now move the code to visual studio and most errors should be fixed. Every so often there will be code that is off-tab, just fix it manually.

梦旅人picnic 2024-08-17 23:07:21

遇到同样的问题,我将代码复制到 jupyter
它向我显示了正确的间距,我用正确的间距替换了错误的间距,它起作用了,

修改了我的文本,我将代码回复制到了 vs code

我实际上复制了正确的行,然后在最后

had the same issue i copied my code to jupyter
it showed me the correct spacing i replaced the wrong spacing with the corrected one and it works

i actually copied correct lines then modified my text

at the end i copied my codeback to vs code

独守阴晴ぅ圆缺 2024-08-17 23:07:21

我在 PyCharm 中遇到了类似的 IndentationError 问题。

我在代码中找不到任何选项卡,但是一旦我删除了带有 IndentationError 的行之后的代码,一切都很好。

我怀疑您在以下行中有一个选项卡:
<代码>
性别 = 性别 如果不是性别 == 2 否则 random.randint(0,1)

I had a similar problem with IndentationError in PyCharm.

I could not find any tabs in my code, but once I deleted code AFTER the line with the IndentationError, all was well.

I suspect that you had a tab in the following line:

sex = sex if not sex == 2 else random.randint(0,1)

你是我的挚爱i 2024-08-17 23:07:21

我从博客复制的代码遇到了这个问题。我通过 Shift+Tab'ing(取消缩进)将最后一个错误抛出代码块一直移到左侧,然后将其按 Tab'ing 返回到原来的位置,从而解决了 PyCharm 上的问题。我想在某种程度上间接地与上面的“重新格式化代码”注释相同。

I had this issue with code that I copied from a blog. I got rid of the issue on PyCharm by Shift+Tab'ing(unindenting) the last error-throwing code-block all the way to the left, and then Tab'ing it back to where it was. I suppose is somehow indirectly working the same as the 'reformat code' comment above.

孤寂小茶 2024-08-17 23:07:21

我建议从头到尾检查你的缩进级别。确保一路使用制表符或一路空格,不要混合使用。我过去遇到过由混合物引起的奇怪的压痕问题。

I would recommend checking your indentation levels all the way through. Make sure that you are using either tabs all the way or spaces all the way, with no mixture. I have had odd indentation problems in the past which have been caused by a mixture.

我的鱼塘能养鲲 2024-08-17 23:07:21

也许是这部分:

if speed      > self.buginfo["maxspeed"]: self.buginfo["maxspeed"] = speed
if generation > self.buginfo["maxgen"]  : self.buginfo["maxgen"]   = generation

尝试删除多余的空间,使其看起来对齐。

编辑:来自 pep8

<前><代码> 是:

x = 1
y = 2
长变量 = 3

不:

x = 1
y = 2
长变量 = 3

尝试遵循这种编码风格。

Maybe it's this part:

if speed      > self.buginfo["maxspeed"]: self.buginfo["maxspeed"] = speed
if generation > self.buginfo["maxgen"]  : self.buginfo["maxgen"]   = generation

Try to remove the extra space to make it look aligned.

Edit: from pep8

  Yes:

      x = 1
      y = 2
      long_variable = 3

  No:

      x             = 1
      y             = 2
      long_variable = 3

Try to follow that coding style.

转身以后 2024-08-17 23:07:21

抱歉,我无法添加评论,因为我的声誉不够高:-/,所以这必须是一个答案。

正如一些人评论的那样,您发布的代码包含几 (5) 个语法错误(两次 = 而不是 ==,并且缺少三个“:”)。

一旦纠正了语法错误,我就没有任何问题,无论是缩进还是其他问题;当然,不可能看到您是否像其他人建议的那样混合了制表符和空格,这可能是您的问题。

但我想强调的真正要点是:
tabnanny 不是真实的:当它实际上只是一个语法错误时,您可能会收到“缩进”错误。

例如。当我添加一个超出必要的右括号时,我得到了它;-)

i += [func(a, b, [c] if True else None))]

会引起 tabnanny 对下一行的警告。

希望这有帮助!

Sorry I can't add comments as my reputation is not high enough :-/, so this will have to be an answer.

As several have commented, the code you have posted contains several (5) syntax errors (twice = instead of == and three ':' missing).

Once the syntax errors corrected I do not have any issue, be it indentation or else; of course it's impossible to see if you have mixed tabs and spaces as somebody else has suggested, which is likely your problem.

But the real point I wanted to underline is that:
tabnanny IS NOT REALIABLE: you might be getting an 'indentation' error when it's actually just a syntax error.

Eg. I got it when I had added one closed parenthesis more than necessary ;-)

i += [func(a, b, [c] if True else None))]

would provoke a warning from tabnanny for the next line.

Hope this helps!

与酒说心事 2024-08-17 23:07:21

Geany 的菜单中有一个选项,显示“应用默认意图”,如果在 Geany 的设置中指定,它将用空格数替换制表符

Geany has an option in its menus that says 'Apply Default Intendation' which replaces tabs by the number of spaces if specified in Geany's settings

幸福还没到 2024-08-17 23:07:21

我也遇到了同样的问题,而且与选项卡无关。这是我的问题代码:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

请注意,上面的 for 比以 if 开头的行缩进了更多空格。这很糟糕。所有缩进必须一致。所以我想你可以说我有一个杂散空间而不是一个杂散标签。

I had this same problem and it had nothing to do with tabs. This was my problem code:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

Note the above for is indented with more spaces than the line that starts with if. This is bad. All your indents must be consistent. So I guess you could say I had a stray space and not a stray tab.

梦途 2024-08-17 23:07:21

我有这个问题。这是因为我的代码中的空格错误。可能是下一行。删除所有空格和制表符并使用空格。

I have this issue. This is because wrong space in my code. probably the next line.delete all space and tabs and use space.

陪你搞怪i 2024-08-17 23:07:21

对于那些已经多次检查代码但没有混合制表符/空格的人:

不仅检查空格/制表符的缩进,还检查空格/制表符的数量。
我的(简化的)错误是这样的:

class dummy:
    def __init__(self):
        pass

    def class_method_1(self):
        print("method1")

    # this is a visible error, but in a complex code, you might miss it
def class_method_2(self):
    print("method2")

    def class_method_3(self):
        print("method3")

python 的错误显示 2 个错误,一个指向 print("method2") 的末尾,一个指向 print("method3") 的末尾。

显然,class_method_2() 是缩进的。

如果您只检查空格(像我一样),您可能会完全错过它,尤其是在更复杂的代码中。

For those who have already checked their code multiple times but there's no mixed tab/space:

Check indentation not only for space/tab, but number of spaces/tabs.
My (simplified) mistake was like this:

class dummy:
    def __init__(self):
        pass

    def class_method_1(self):
        print("method1")

    # this is a visible error, but in a complex code, you might miss it
def class_method_2(self):
    print("method2")

    def class_method_3(self):
        print("method3")

with python's error showing 2 errors, one pointing at the end of print("method2"), one at the end of print("method3").

Obviously, class_method_2() is underindented.

If you only check for spaces (like me), you can miss it completely, especially in a more complex code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文