Firstly there is the problem of indentation here please correct that and adding a little white space at the end of function makes things clear.
def some_func(count):
if count > 0:
some_func(count-1)
print(count)
print(some_func(5))
The reason is, in recursion the code next to the recursive call is put into a stack memory which is a Last in First Out structure, you can find more about it here stack and until the termination condition for the code comes up the pushes of subsequent statements keep happening on to the top of the stack.
A sample visualization of what happens after you call the print(some_func(5))
print(some_func(5)):
5>0 => True, so the next cmd some_func(5-1) is called at this point something interesting happens, in the stack space all the subsequent statements of some_func(count-1) are pushed and then the actual method invocation starts, so at this point in time the stack will look like this:
| TOP_OF_STACK |
|--------------|
| print(5) |
- Next line to get invoked is some_func(4):
then again 4>0 => True
so some_func(4-1) is called and the subsequent print(4) is pushed on to the stack as shown below:
| TOP_OF_STACK |
|--------------|
| print(4) |
|--------------|
| print(5) |
- some_func(3):
3>0 => True,
call some_func(3-1) and push print(3) on to the top of the stack.
| TOP_OF_STACK |
|--------------|
| print(3) |
|--------------|
| print(4) |
|--------------|
| print(5) |
Same thing goes on for some_func(2) and some_func(1) by the end of which stack looks like this:
| TOP_OF_STACK |
|--------------|
| print(1) |
|--------------|
| print(2) |
|--------------|
| print(3) |
|--------------|
| print(4) |
|--------------|
| print(5) |
When some_func(0) is called the following thign happens:
0>0 => false so no further statements following if will be called and all the statements that have been pushed on to the stack so far will be popped out sequentially from the top, which results in the execution of the print statements resulting in the output:
1
2
3
4
5
Additionally one possible reason why you may encounter stack overflow errors for recursive code sometimes is because if your terminal condition is not a valid one then the pushes keep on happening until a point there is no space left out in the memory!
Hope this gives you better understanding of the recursive flow.
count > 0it will never enter this block ifcountis0then it will not print0print(some_func(5))is inside the function or not. It doesn't really make sense since the function doesn't return anything.some_func(4), some_func(3), some_func(2), some_func(1)) before printing out the parent count number. so it print out the final child and came back to the parent functions. you can't print out 0 as you setcount > 0so it can only reach 1