我无法理解为什么python会出现“预期的缩进块”错误?
""" This module prints all the items within a list"""
def print_lol(the_list):
""" The following for loop iterates over every item in the list and checks whether
the list item is another list or not. in case the list item is another list it recalls the function else it prints the ist item"""
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item)
else:
print(each_item)
答案 0 :(得分:25)
你必须在函数定义之后缩进docstring(第3,4行):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
缩进的:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
或者您可以使用#
发表评论:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
另外,您可以看到关于文档字符串的PEP 257。
希望这有帮助!
答案 1 :(得分:4)
我也经历过例如:
此代码不起作用并获得预期的块错误。
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
但是,当我在键入return self.title语句之前按Tab键时,代码可以正常工作。
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
希望,这会有所帮助。