nick
nick

Reputation: 1

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

Upvotes: 0

Views: 1634

Answers (2)

Maxence SCHMITT
Maxence SCHMITT

Reputation: 629

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.

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 602285

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.

Upvotes: 8

Related Questions