I have an exercise with following code:
def rec_count(number):
print(number)
# Base case
if number == 0:
return 0
rec_count(number - 1) # A recursive call with a different argument
print(number)
rec_count(5)
which gives this output:
5
4
3
2
1
0
1
2
3
4
5
I don't understand why after reaching 0 function doesn't go on with negative numbers, and gives numbers from 1 to 5 instead. Can someone explain?
Thanks in advance
CodePudding user response:
Regarding negative numbers: when rec_count(0) is called, we encounter a return statement before reaching rec_count(0-1). As soon as a return statement is reached, execution of the function ends, so rec_count(-1) is never called.
Regarding increasing numbers: note that there is a print(number) statement after the recursive rec_count call.
CodePudding user response:
This has to do with the second print statement you have after the recursive call. When rec_count is called, the first print statement is hit and the expected print outs happen (5,4,3,2,1). The base case is also hit as expected. However, that is when the cascaded returns happen, and then the second print statement is hit in reverse order, resulting in the extra print outs you see.
CodePudding user response:
once you use return statement will end a function it is continuing the count from 0 to 5 because you called that function and it didnt end
a Good solution would be to do something like the following
def rec_count(number):
print(number)
for i in range(number*2):
number = number - 1
print(number)
rec_count(5)
