短 Python 函数 returning None,当存在显式 return 语句时

Short Python function returning None, when explicit return statement present

我正在研究 CodeWars kata(递归反向字符串),但我总是得到错误的答案。我有以下文件 test.py

def reverse(s):
    if len(s) == 1:
        return s
    return s

print(reverse("dlrow olleh"))

从与 test.py 相同的目录中的新终端执行的整个过程如下:

brandonheinrich:~/workspace (nesting) $ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
None
>>> 
brandonheinrich:~/workspace (nesting) $ 

直接 运行 时也会发生同样的行为。

brandonheinrich:~/workspace (nesting) $ python test.py
None
brandonheinrich:~/workspace (nesting) $ 

根据要求:

>>> print repr(open("test.py").read())
'def reverse(s):\n    if len(s) == 1:\n        return s\n\treturn s\n\t\nprint(reverse("dlrow olleh"))'

谁能解释一下为什么会这样 return None

它是相关的,我在 CodeWars 解释器和 Python 2.7.6,Cloud9 上的 运行ning 上都遇到了这个错误。

您混用了制表符和空格。 return 语句实际上都在 if 中。在编辑器中打开 "show whitespace" 以查看它,并使用 -tt 标志打开 运行 Python 以使其抱怨模棱两可的缩进。