Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this happen when using recursion in python? [duplicate]

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

like image 950
Hewen Chen Avatar asked May 25 '26 23:05

Hewen Chen


1 Answers

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.

like image 164
saedx1 Avatar answered May 28 '26 11:05

saedx1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!