程序输出中包含“None”... 为什么?
我在论坛上搜索过,发现了一些类似的问题,但还是没能解决我的困扰。
我的代码是用递归的方法来交换每个单词中每两个字母的位置,并打印出结果。对于字母数量是偶数的单词,输出中会包含一个“None”,我不知道该怎么修复这个问题……
这是我的代码:
def encryptLine(line, count):
headline = line[count:]
if length(headline) > 0:
if count == length(line) - 1:
new = headline
return new
elif count <= length(line):
new = head(tail(headline)) + head(headline)
new = new + str(encryptLine(line, count+2))
return new
print(encryptLine('abcd', 0))
对于'abcd'的输出是bADCNone,除了“None”这个词外,其他都是正确的。对于'abcde'的输出是'badce',这个是正确的……
提前感谢你的帮助!
2 个回答
2
这里没有值是因为你的函数没有返回任何东西。
有一个情况是你没有返回任何东西,就是
if length(headline) <= 0:
在Python中,如果一个函数没有返回值,而你又试图去获取这个返回值,那么得到的值就是None。
8
在函数定义里加上 return ""
,也就是说:
def encryptLine(line, count):
headline = line[count:]
if length(headline) > 0:
if count == length(line) - 1:
new = headline
return new
elif count <= length(line):
new = head(tail(headline)) + head(headline)
new = new + str(encryptLine(line, count+2))
return new
return ""
否则,如果 length(headline) > 0
这个条件不成立,函数就会返回 None
。