I need a recursive counter in python counting from 1 to n.
def countup(n):
a=1
def hoch(a,n):
if a<=n:
print(a)
a+=1
hoch(a,n)
hoch(a,n)
I need a recursive counter in python counting from 1 to n.
def countup(n):
a=1
def hoch(a,n):
if a<=n:
print(a)
a+=1
hoch(a,n)
hoch(a,n)
Here is a solution.
def countup(n):
if n >= 0:
countup(n - 1)
print(n)
countup(10)
Basically, if the number passed into countup
is greater than 0, it recursively runs countup
again, passing into it the next number below.
It only uses 1 function.
P.S. It already existed here:
You can do very simple without recursion, which is not the ideal way to go.
def countup(n):
print(*range(n + 1), sep='\n')
Assuming you have to do this recursively (which isn't the best way to do it), another option is to pass a
to countup()
as an optional argument.
def countup(n, a=1):
if a <= n:
print(a)
countup(n, a+1)
countup(10)