Home > other >  Why does this happen when using recursion in python?
Why does this happen when using recursion in python?

Time:09-22

I am learning resursion recently and I wrote a simple recursive function to verify my understanding:

def hello(n):
    if n == 1:
        return 'hello'
    else:
        print('hello')
        hello(n-1)

def returnhello():
    return 'hello'

print(returnhello())
print()
print(hello(5))

the output of this is shown here:

hello

hello
hello
hello
hello
None

Why the last call in the recursion prints None instead of hello? I was expecting it to print 5 hello

CodePudding user response:

This is because in your else part in hello(n) you don't have a return statement before hello(n-1), so the first call (exiting the last) will return a None.

If you put a return before hello(n-1) you should get what you want.

CodePudding user response:

The right recursion function for your expected output is:

def hello(n):
    if n == 1:
        return 'hello'
    else:
        print('hello')
        return hello(n-1)

def returnhello():
    return 'hello'

print(returnhello())
print()
print(hello(5))

Also, it can be written as:

def hello(n):
    if n==1:
        print("hello")
    else:
        print("hello")
        hello(n-1)
        
def returnhello():
    return 'hello'

print(returnhello())
print()
hello(5)

The output will be:

hello

hello
hello
hello
hello
hello

Note:

You mustn't use print with a recursive function, you can use a function with return statement or without any statement.

CodePudding user response:

@saedx has identified and corrected your issue. Python returns None by default and that is what you see printed after the function returns.

You could implement your hello function to be a bit more consistent in how it displays the strings. At present the first n-1 are printed in the body of the function but the caller is left to print the final one.

Here the function prints all n of the strings.

def hello(n):
    print('hello')
    if n > 1:
        hello(n-1)

hello(5)

In this case you just call the function. You don't print what it returns.

The other way would be to have the caller print all n of the strings.

def hello(n):
    yield 'hello'
    if n > 1:
        yield from hello(n-1)

Which is then called like

print('\n'.join(hello(5)))

Also note that both these examples remove the duplication of the string being printed. Its worth noting that if you passed in a number less than 1 you'd be in trouble, as it would recur infinitely. So we could throw an exception in that case.

  • Related