开发者

"None" included in program output... why?

i've searched the forum and found similar questions, but no luck in solving my problem.

My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and开发者_运维技巧 i don't know how to fix...

here's the code:

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

the output for 'abcd' is badcNone, which is correct except for the word None. the output for 'abcde' is 'badce', which is correct...

thanks in advance for your help!


Add return "" to the function definition, that is

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 ""

Otherwise, the function will return None if length(headline) > 0 does not hold.


None is here because your function return nothing. There is 1 case where you return nothing it is

if length(headline) <= 0:

In Python, if there is no return to a function and you try to access to a return value, the value will be None.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜