Say*_*iss 3 python syntax python-idle
我在 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()
Run Code Online (Sandbox Code Playgroud)
我是 Python 新手,不知道如何修复此代码。
您没有正确缩进代码。您的方法的主体缩进正确,但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
Run Code Online (Sandbox Code Playgroud)
块语句的主体是 a 之后的任何内容,:它需要适当缩进。例如:
if 'a' == 'b':
print('This will never print')
else:
print('Of course a is not equal to b!')
Run Code Online (Sandbox Code Playgroud)
如果你这样输入:
if 'a' == 'b':
print('This will never print')
else:
print('Of course a is not equal to b!')
Run Code Online (Sandbox Code Playgroud)
它不是有效的 Python 语法。