42

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
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Rob
  • 421
  • 1
  • 4
  • 3
  • Nothing apparent to the eye. As suggested in responses, probably a matter of mixed tabs/spaces. Or something from the Gods, unhappy about ALife projects ;-) – mjv Nov 10 '09 at 22:45
  • 1
    this is not the code you're running. you don't have `def new` on line 53 (it's on line 37), this posted code produces `SyntaxError` on line 54. – SilentGhost Nov 10 '09 at 23:03
  • You can try viewing the file in notepad++ with showing all characters. You would be able to see tabs and space if they both are used for indentation. – Gaurav Parek Aug 10 '21 at 08:23
  • Does this answer your question? [IndentationError: unindent does not match any outer indentation level](https://stackoverflow.com/questions/492387/indentationerror-unindent-does-not-match-any-outer-indentation-level) – Tomerikoo Jan 24 '22 at 08:44

17 Answers17

67

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>
  • I've tried that, got Bugs.py 31 ' self.sex = ["Male", "Female"]\n' checked the tabs/spacing and it seems to be fine – Rob Nov 10 '09 at 22:53
  • 3
    @Rob: If you got an error, then "seems to be fine" is a judgement that might be incorrect. Replaces all tabs with spaces. – S.Lott Nov 11 '09 at 00:22
  • @S.Lott - By "it seems to be fine" I meant I did that about 4 times before posting here on any lines that tabnanny gave me. It never returned any of the lines that actually had the problems. – Rob Nov 11 '09 at 03:41
  • 2
    very helpful for python beignner – andyqee May 30 '13 at 07:03
20

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

Riv
  • 323
  • 2
  • 8
11

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.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • that was strange, I finally went and found a tab character to put in find & replace and it found 4 tabs thrown randomly around in my code. Thanks – Rob Nov 10 '09 at 22:58
  • 1
    And this is just one reason I find significant whitespace a really bad idea. – Svante Nov 10 '09 at 23:29
  • 2
    I think the problem is allowing tab=n spaces in the language. You're fighting a lost battle if you fight significant whitespace, and there's a good reason for that. – Alice Purcell Nov 11 '09 at 23:30
8

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

Pete
  • 81
  • 1
  • 1
3

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.

Saif Hakeem
  • 875
  • 8
  • 9
2

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

Fahd Mannaa
  • 295
  • 2
  • 7
2

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

jomyfrancis19
  • 31
  • 1
  • 1
  • 3
1

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.

Wlliam
  • 175
  • 4
  • 12
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)

IvanD
  • 7,971
  • 4
  • 35
  • 33
1

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.

mvishnu
  • 1,150
  • 1
  • 12
  • 15
0

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

oneindelijk
  • 606
  • 1
  • 6
  • 18
0

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.

Loïc Wolff
  • 3,205
  • 25
  • 26
  • Besides, you have a lot of `if i = x`, it should be `if i == x`. And you missed some ":" at the end of some method – Loïc Wolff Nov 10 '09 at 22:49
  • I know, I'm somewhat sloppy and just catch it all later when I test :) – Rob Nov 10 '09 at 22:59
  • I looked through the code and I don't see `if i = x` anywhere. And `if i = x` shouldn't even work in Python! The compiler won't even let you do that! @dex, which line(s) are you talking about? – steveha Nov 11 '09 at 00:54
0

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.

Wayne Koorts
  • 10,861
  • 13
  • 46
  • 72
0

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.

Freddie
  • 908
  • 1
  • 12
  • 24
0

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!

Stefano
  • 18,083
  • 13
  • 64
  • 79
0

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

yasin lachini
  • 5,188
  • 6
  • 33
  • 56
0

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.