【问题标题】:"Expected an indented block" error?“预期缩进块”错误?
【发布时间】:2013-10-29 11:57:44
【问题描述】:

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

【问题讨论】:

  • 嗯...为什么是文字图片?只发布实际代码会更有意义......毕竟不是那么多:)可能也会更快。
  • 您必须在第 3 行缩进文档字符串。
  • 如果可以,请考虑在此处粘贴代码,而不是发布图片。
  • n-thing 代码截图很愚蠢的想法。此外,您必须缩进文档字符串的原因 是它们不是 cmets。它们是实际的字符串对象,由解析器附加到它们所针对的模块/类/函数(作为__doc__ 属性),因此它们必须在解析树中的位置。
  • 我很想知道您使用的是什么编辑器,这使得截屏然后裁剪比复制和粘贴更简单:)

标签: python indentation docstring


【解决方案1】:

你必须在函数定义之后缩进文档字符串(第 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 关于文档字符串的信息。

希望这会有所帮助!

【讨论】:

  • 只是小费。当您使用 cmd 窗口逐行执行 python 时,它会在第二行的开头显示一个...。您仍然必须在输入所有内容之前按Tab 键以避免此错误。
【解决方案2】:

我也经历过,例如:

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

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

希望,这将对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多