I am trying to write a recursive function that prints from 0
to n
, but I have no idea how to do it. I accidentally made one that prints from
You almost got it! here's a fixed, simplified version:
def countup(n):
if n >= 0:
countup(n - 1)
print(n)
Notice that:
print
statement must be placed after the recursive calln < 0
, given that we're only printing, there's nothing left to be done afterwards and it's ok to return None
(Python's default return value)UPDATE
It seems that writing a tail recursive solution is all the rage around here :) oh well, here's my shot at it, a simplified and tail-recursive version of @AndyHayden's idea - using the tail call optimization decorator recipe:
@tail_call_optimized
def countup(N, n=0):
print(n)
if n < N:
countup(N, n + 1)
Either way, it works as expected:
countup(5)
=> 0
1
2
3
4
5