How to write a recursive function to print a string a certain number of times?
<p>I have been trying to write a python function which will receive two arguments: <code>x</code> which is the number of times to repeat and <code>y</code> which is the number or string to be repeated.</p>

<p>So far this is what I have been able to come up with, but I can't seem to be able to determine how to do it recursively.</p>

<pre><code>def recurse(x, y):
    final = []
    if x == 0:
        return ("")
    else:
        x = x - 1
        final.append(recurse(x,y))              
    return final
</code></pre>

<p>If <code>recurse(3,"Cat")</code> is called, the output is meant to look like this:</p>

<pre><code>print recurse(3, 'cat')
['cat','cat','cat']
</code></pre>

<p>How would I go about doing this?</p>

<pre><code>def recurse(x, y):
    final = []
    if times == 0:
</code></pre>

<p>You can't just reference "times" as if it's some kind of magic floaty variable available anywhere and everywhere. The first time in here, <code>times</code> will have no value. And the next time through, you're hoping you can just pick the value of <code>times</code> out of thin air and it will magically be what it was somewhere else, during some previous run.</p>

<p>The only variables you can work with are the ones completely inside your function - or ones which are passed in from outside, and returned out at the end.</p>

<pre><code>def recurse(times, word):
    if times == 1:
        return [word]
    else:
        return [word] + recurse(times-1, word)

print(recurse(3, 'cat'))
</code></pre>

<p><a href="https://repl.it/Dbbl" rel="nofollow">Try it online at repl.it</a></p>

<p>It takes a number of times as an input, it returns <code>[word]</code> plus ( It takes a number of times - 1 as an input, it returns <code>[word]</code> plus ( It takes a number of times - 1 as an input, it returns <code>[word]</code> ).</p>

<p>Note there's no accumulator list like <code>final = []</code> because each time through the function it will be empty again. The accumulation happens implicitly in the way the programming language calls functions and returns values. Python will hold <code>[word]</code> in memory itself while it calculates the next recurse() output.</p>

python recursion