0

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)
Bahamas
  • 345
  • 1
  • 2
  • 13
  • As someone from Germany you should know the wise words "Wieso einfach, wenn es auch kompliziert geht?" (*Why simple if it can be done complicated?*) – Klaus D. Mar 11 '18 at 15:23
  • What's wrong with `for x in range(1,n): print(x)` ? How is this 'recursive' ? – match Mar 11 '18 at 15:27

3 Answers3

1

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:

python recursive function that prints from 0 to n?

Pang
  • 9,564
  • 146
  • 81
  • 122
kale
  • 151
  • 1
  • 10
0

You can do very simple without recursion, which is not the ideal way to go.

def countup(n):
    print(*range(n + 1), sep='\n')
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
0

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)
SCB
  • 5,821
  • 1
  • 34
  • 43