This is a simple recursive function that should run 10 times, the condition is if.
count = 0
def recurse(count):
*if* count < 10:
print count
count += 1
recurse(count)
recurse(count)
Output
0 1 2 3 4 5 6 7 8 9
OK
When I use a while loop, the results are wildly different and I don't understand why it does not output 0 to 9.
Code
count = 0
def recurse(count):
*while* count < 10:
print count
count += 1
recurse(count)
recurse(count)
Output
0 1 2 3 4 5 6 7 8 9 9 8 9 9 7 8 9 9 8 9 9 6 7 8 9 9 8 9 9 7..... 8 9 9
You can try it here https://repl.it/nHa/3, I don't know how to create a link with the code though.
anyone see what I am doing wrong.
Edit.
Output of code 2 is finite.
Example using 3 as a limit.
0 1 2
https://repl.it/nHa/30 1 2 2 1 2 2
https://repl.it/nHa/2You need to return recurse in the if block:
count = 0
def recurse(count):
if count < 10:
print(count)
return recurse(count+1)
In [63]: recurse(0)
0
1
2
3
4
5
6
7
8
9
And do the same in the while block:
def recurse(count):
while count < 10:
print(count)
count += 1
return recurse(count)
A graph showing the recursive calls and the order may help:
We start at 0 then recurse on 1, 2 and finally 3, then we move to 2 recurse again to 3 and finally we reach the last number 3 and the function ends.
Now what happens when you return:
What the colour and numbering means:
Note: 1. The edges are numbered by the order in which they were traversed by the execution. 2. The edges are colored from black to grey to indicate order of traversal: black edges first, grey edges last.
The graph was generated using rcviz
The problem is that count
is local to each of the function that you are calling! Hence each time you have a recursive function call you will iterate the loop again! Thus your base-case is never satisfied. Use return
and you will get your desired output. This is because you will then save the state of the variable count
. (The other way is to make count a global variable, which is a bad way to go)
count = 0
def recurse(count):
while count < 10:
print count
count += 1
count = recurse(count)
return count
recurse(count)
In this you are re-assigning the count value back to your variable in the outer recursive functions, hence your base case will be satisfied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With