Search code examples
pythonsyntaxpython-idle

SyntaxError: invalid syntax when creating a instance of class


I run this code in Python shell 3.3.2, but it gives me SyntaxError: invalid syntax.

class Animal(object):
    """Makes cute animals."""
    is_alive = True
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def description(self):
        print (self.name)
        print (self.age)

hippo = Animal("2312",21)#error occurs in that line
hippo.description()

I'm a newbie in Python and I don't know how fix this code.

Screenshot from IDLE


Solution

  • You didn't indent your code properly. The body of your methods is indented correctly, but you forgot to indent the doc string, and the def statement for your methods, in addition to the is_alive = True statement. If you type it in IDLE like this, it will work:

    >>> class Animal(object):
    ...     """Makes cute animals."""
    ...     is_alive = True
    ...     def __init__(self, name, age):
    ...         self.name = name
    ...         self.age = age
    ...     def description(self):
    ...         print(self.name)
    ...         print(self.age)
    ...
    >>> hippo = Animal("2312", 21)
    >>> hippo.description()
    2312
    21
    

    The body of a block statement is anything that comes after a :, and it needs to be properly indented. for example:

    if 'a' == 'b':
        print('This will never print')
    else:
        print('Of course a is not equal to b!')
    

    If you type it like this:

    if 'a' == 'b':
    print('This will never print')
    else:
    print('Of course a is not equal to b!')
    

    It is not valid Python syntax.