Andrew Louis Andrew Louis - 1 month ago 17
Python Question

Repeat a string n times and print n lines of it

i've been stuck on a question for some time now:

I'm looking to create a python function that consumes a string and a positive integer. The function will print the string n times, for n lines. I cannot use loops, i must only use recursion

e.g.

repeat("hello", 3)

hellohellohello
hellohellohello
hellohellohello


whenever i try to make a function that does this, the function decreases the length of the string, progressively:

e.g.

repeat("hello", 3)

hellohellohello
hellohello
hello


here's what my code looks like:

def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)


any help would be appreciated, thanks!

Answer

Try this

def f(string, n, c=0):
    if c < n:
        print(string * n)
        f(string, n, c=c + 1)

f('abc', 3)