在函数外返回,或意外缩进
我有这个:
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
它告诉我“return”在函数外面。
当我把它改成这样:
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
它只是告诉我有一个意外的缩进。我该怎么解决这个问题呢?
2 个回答
0
在 if colorkey is not None:
这行代码后面,有两个缩进,其实只需要一个就可以了。
4
在Python中,作用域是通过相同的缩进级别来定义的,而不是像其他语言那样用大括号(也就是{}
)。
如果你写一个函数,确保函数内部的所有代码都在同一个缩进级别上——无论是用相同数量的空格还是相同数量的制表符(混合使用空格和制表符会导致很麻烦的情况)。
在你的例子中,正确的缩进应该像这样(我不太确定,因为你没有贴出整个函数的代码):
def function():
<indent>if colorkey is not None:
<indent><indent>if colorkey is -1:
<indent><indent><indent>colorkey = image.get_at((0,0))
<indent>image.set_colorkey(colorkey, RLEACCEL)
<indent>return image, image.get_rect()