I'm working on a fairly basic function, and I'm finding it difficult to figure out why I get my output.
def mystery(n):
print(n)
if n < 4:
mystery(n + 1)
print(n)
mystery(1)
This is my output:
1
2
3
4
4
3
2
1
I think I am clear on the first part of the output , n < 4 so we are adding 1 each time, then when we get to 4, the function skips the if part and prints(n) which is 4 again. I'm then a bit lost though why the output counts back down to 1. I'm guessing there is some really obvious part of recursion that I am overlooking, thanks for your help.
mystery
), it goes back into the previous function it came from, and does the second print.if
part because the condition4 < 4
is false. Then, since every previous call of your mystery function has been completed in theif
condition, it continues the program flow in the next line which is the lastprint(n)
, printing all values from3
to1
.