python - 返回外部函数,或意外缩进

标签 python return indentation

我有这个:

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()

它只是告诉我有一个意外的缩进。我该如何解决这个问题?

最佳答案

在 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()

关于python - 返回外部函数,或意外缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5626889/

相关文章:

Python 将回车符视为换行符。我能做什么呢?

python - 使用 spaCy NLP 的简单 Flask 应用程序间歇性挂起

ruby - 如何取消评估所需的 Ruby 文件? (又名顶级返回)

c++ - 何时在函数外部返回值使用 move 与复制?

python - 将 Python 的 stdout 传递给写入的 C 函数

python - 如何用字典值替换 Pandas Series

C# Blank else 如果不好的做法要转义?

perl - 如何在 Perl POD 中记录参数

c - return 1 和 return(1) 有什么区别?

visual-studio - Visual Studio : any one click switch between tabs and spaces indentation?