20

我不明白为什么 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)
4

2 回答 2

31

您必须在函数定义之后缩进文档字符串(第 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

希望这可以帮助!

于 2013-10-29T12:02:08.153 回答
5

我也经历过,例如:

此代码不起作用并得到预期的块错误。

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

希望,这会帮助其他人。

于 2014-06-30T11:52:44.687 回答