I need a recursive (exercise) function that prints all natural numbers between A and B :
def cont(a, b):
if a < b:
print(a)
cont(a + 1, b)
cont(-3, 12)
The problem is that the way I did, the negative numbers are being printed as well.
I need a recursive (exercise) function that prints all natural numbers between A and B :
def cont(a, b):
if a < b:
print(a)
cont(a + 1, b)
cont(-3, 12)
The problem is that the way I did, the negative numbers are being printed as well.
You have two distinct conditions, one is the condition of what should be printed, and should be all numbers greater than or equal to zero, the other condition is how long recursion should continue.
def cont(a, b):
if a >= 0:
print(a)
if a < b:
cont(a + 1, b)
cont(-3, 12)
See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .
You can do an intermediate function to avoid recursion in unnecessary items, that is, to start from scratch. Just as iteratively, what aliasing is the best way to do this kind of algorithm. I do not like these exercises that force the use of recursion.
And there is no validation if the first argument is less than the second, which should even be done in this intermediate function that I said.