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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With