Junchao Gu
Junchao Gu

Reputation: 1865

python class definition -- name undefined or unexpected indent

class Animal(object):

        """Makes cute animals."""
        is_alive = True
        def __init__(self, name, age):
        self.name = name
        self.age = age
    # Add your method here!
    def description(self):
        print self.name
        print self.age

hippo = Animal("Steve",100) 
hippo.description() 

--code piece one

the error I got:

Traceback (most recent call last):
  File "runner.py", line 125, in compilecode
  File "python", line 3
    is_alive = True
   ^
IndentationError: unexpected indent

no idea of what is happening

can anybody please tell me where I am wrong? thanks a lot!

Upvotes: -1

Views: 2515

Answers (3)

abarnert
abarnert

Reputation: 365657

It looks like you're mixing tabs and spaces. This means that what you see as the indentation, and what the interpreter sees, are completely different. Which will lead to hard-to-notice IndentationErrors.

In particular:

        """Makes cute animals."""
        is_alive = True
        def __init__(self, name, age):
        self.name = name

The first two lines have 8 spaces. The third has 7 spaces and a tab. I'm not sure whether Python treats that as more indented than 8 spaces—which is an error, because there's no reason to indent here—or just refuses to guess which one counts as more indentation than the other. But either way, it's wrong. And then the next line has 2 tabs.

To fix this code, delete all the tabs, and re-indent with spaces.

The simple way to avoid this in the future is to never use tabs in your code.

You also may want to consider using a better editor, that will always insert spaces, even if you hit the Tab key. Or, failing that, at least and editor that can show you tabs, so you can spot the problems when they arise.

Finally, whenever you get IndentationErrors when the code looks perfectly fine, try running your code with the -t flag (python -t myscript.py instead of python myscript.py) to check whether this is the reason.

PEP 8 (the Python style guide) has a section on this.

Upvotes: 4

Mark Hildreth
Mark Hildreth

Reputation: 43061

Make sure you are not mixing up tabs and spaces for how you indent. Pick to use all tabs, or all spaces.

Upvotes: 0

Josh
Josh

Reputation: 1385

You need to indent self.name and self.age lines like so.

class Animal(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

You have to indent text below methods you define.

Upvotes: 0

Related Questions