def print_numbers(n):
if n == 1:
print(n)
print("recursion over")
else:
print_numbers(n-1)
print(n)
print_numbers(10)
the output is
1
recursion over
2
3
4
5
6
7
8
9
10
Why do the numbers keep increasing instead of decreasing into the negatives?? I know I never returned anything or technically ended the code but is that necessary? I just want to understand this
CodePudding user response:
Why do the numbers keep increasing instead of decreasing into the negatives??
They don't. The issue is that you print()
the value of n
after your recursive call, so you don't perform any print statements until you've decremented n
to 1
, after which you "rewind" up the stack of recursive calls...first printing "1" and "recursion over" in your terminal state, then walking back up until you finally return to the original caller.
If you place the print
statement before the recursive call, like this:
def print_numbers(n):
if n == 1:
print(n)
print("recursion over")
else:
print(n)
print_numbers(n-1)
print_numbers(10)
You get different output:
10
9
8
7
6
5
4
3
2
1
recursion over
CodePudding user response:
Consider your code. I have added a print statement before it to help explain it.
def print_numbers(n):
print('n value is', n)
if n == 1:
print(n)
print("recursion over")
else:
print_numbers(n-1)
print(n)
print_numbers(3)
This gives an output of
n value is 3
n value is 2
n value is 1
1
recursion over
2
3
Why?
Well, when the parameter n
is passed through, its value is 3, and prints 'n value is 3'. So far so good. But when you get to the if statement, n
is not one, so it executes the same function with n-1
, however, it does not print, because it has called the function and needs to execute first. So instead the function runs again, this time with the value 2. This keeps happening until 1, and then all the print statements that have been put on hold execute.
A simple way to fix this is just to put the print statement BEFORE the function:
def print_numbers(n):
if n == 1:
print(n)
print("recursion over")
else:
print(n)
print_numbers(n-1)
print_numbers(10)
This prints
10
9
8
7
6
5
4
3
2
1
recursion over
As intended