Python: “Indentation Error: unindent does not match any outer indentation level”

允我心安 提交于 2021-01-20 14:54:38

问题


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

回答1:


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>



回答2:


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




回答3:


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.




回答4:


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




回答5:


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...




回答6:


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




回答7:


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.




回答8:


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)




回答9:


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.




回答10:


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.




回答11:


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!




回答12:


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




回答13:


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.




回答14:


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




回答15:


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.




回答16:


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.



来源:https://stackoverflow.com/questions/1711756/python-indentation-error-unindent-does-not-match-any-outer-indentation-level

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!