I have the following for my first function (array defined under function):
def test(array):
if len(array) == 1:
return 1
return test(array[: -1]))
array = [1, 2, 3]
test(array)
It returns:
1
What I thought was happening was that this 1 was being returned up through the two recursive calls until it is outputted to the GUI when it is returned to the original call.
I wrote a modified second function where I replace "return test(array[: -1])" with "return print(test(array[: -1])" to confirm by belief, but I get the following output:
1
None
So shouldn’t I receive a "None" or some kind of error instead of a 1 in the first function’s output? What does "None" here actually mean?
>Solution :
Your first function is working as it should. In the first function you are recursively removing the last element of the array until the array has only one element inside, and when that is true it returns 1.
When you changed return test(array[: -1]) for return print(test(array[: -1]) you are now doing 2 things:
- You are printing the return value of the function
testwhich as you saw in the first case, will be 1. - You are returning the value of the function
printwhich isNone.
So, both scenarios are working accordingly.