PyCharm 显示 "PEP8: expected 2 blank lines, found 1"

PyCharm shows "PEP8: expected 2 blank lines, found 1"

考虑以下代码:

def add_function(a, b):
    c = str(a) + b
    print "c is %s" % c

def add_int_function(c, d):
    e = c + d
    print "the vaule of e is %d" % e

if __name__ =="__main__":
    add_function(59906, 'kugrt5')
    add_int_function(1, 2)

它总是向我显示:"expected 2 blank lines ,found 1" 在 add_int_function 中,但在 add_function 中却没有。

当我在def add_int_function(c, d):前面加两个空格 有一个错误显示 unindent does not match any outer indentation leveladd_function 结束时:

只需在您的函数定义之间添加另一行:

1 行:

2 行:

这是 python 社区中一个很常见的问题。 PEP 8 发布后,python 接受了新的格式样式。其中之一指出,在 class 或函数的定义之后,必须有两行分隔它们。因此:

    def yadayada:
     print("two lines between the functions")


    def secondyadayada:
     print("this is the proper formatting")

所以,你永远不应该这样做:

    def yadayada:
     print("two lines between the functions")

    def secondyadayada:
     print("this is the proper formatting")

否则 PyCharm 会向您抛出该错误。

关于@kennet-celeste 和@shreyshrey 的回答的进一步说明,

定义的每个函数或class需要上方2个空格下方2个空格。除非该函数是脚本中的最后一项,其中预期的格式是一个空行作为文件结束标记。所以:

# some code followed by 2 blank spaces


def function1():


def function2():


def function3():

对于想知道为什么需要两个空行的人

如果你用其他语言写作,那就是:

fun doSth() {
    print()
}

fun doSth1() {
    print()
}

但是如果您要从代码中删除所有花括号,您将看到:

方法之间有两个空行

fun doSth()
    print()
#
#
fun doSth1()
    print()
#