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
>Solution :
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.