我在python shell 3.3.2中运行该代码,但是它给了我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()
我是python的新手,我不知道该如何修复该代码。谁能给我一些建议?预先感谢。
在IDLE中切换为屏幕:
您没有正确缩进代码。方法的主体已正确缩进,但是除了def
语句之外,您还忘记了为文档字符串和方法的is_alive = True
语句缩进。如果您以这种方式在IDLE中输入内容,它将可以正常工作:
>>> 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
block语句的主体是:
之后的任何东西,需要适当缩进。例如:
if 'a' == 'b':
print('This will never print')
else:
print('Of course a is not equal to b!')
如果您这样输入:
if 'a' == 'b':
print('This will never print')
else:
print('Of course a is not equal to b!')
这不是有效的Python语法。