2

I need to do a countup value that prints as a string -- so if the user would enter 5 it would count up from 1 -- ' 1 2 3 4 5' in a string and not seperate lines. This is what i have for a basic recursion function that counts up however it is not giving me the output of a string. Any help would be much appreciated

def countup(N, n=0):
    print(n)
    if n < N:
        countup(N, n + 1)
sheldonzy
  • 5,505
  • 9
  • 48
  • 86
ellezi
  • 39
  • 1
  • 4

3 Answers3

1

If you need to return a string, think about returning strings. The first part of your result is n converted to a string: str(n). While you're not yet done, you append a space followed by the countup of the rest of the numbers. Like so:

def countup(N, n=1):
    res = str(n)
    if n < N:
        res += ' ' + countup(N, n + 1)
    return res

print(countup(5))

Another version, without the need of a local variable, is:

def countup(N, n=1):
    if n < N:
        return str(n) + ' ' + countup(N, n + 1)
    else:
        return str(n)
JohanC
  • 71,591
  • 8
  • 33
  • 66
1

Why not just use str.join? No recursion needed here.

def countup(N, n=1):
    return ' '.join(map(str, range(n, N)))
Jab
  • 26,853
  • 21
  • 75
  • 114
0

For start, this is a basically a duplicate of python recursive function that prints from 0 to n? and recursion, Python, countup, countdown

Change your ending of the print with print(n, end = ' ') to avoid the new line. See How to print without newline or space?

Also, your default argument should be n=1 to comply with it would count up from 1 assuming the call of countup(5)

def countup(N, n=1):
    print(n, end = ' ')
    if n < N:
        countup(N, n + 1)