Python recursion variable state
<p>I'm trying to write a Python function to take a string and a number and return a list containing repetitions of the string. For example</p>

<pre><code>print func(3, 'aaa')
</code></pre>

<p>returns</p>

<pre><code>['aaa', 'aaa', 'aaa']
</code></pre>

<p>This is what I've done so far:</p>

<pre><code>def func(times, data):
    if times &gt; 0:
        return data.split() + func(times-1, data)
</code></pre>

<p>However, it's giving me a TypeError:</p>

<pre><code>can only concatenate list (not "NoneType") to list.
</code></pre>

<p>I'm still a novice and I just read about recursion. </p>

<p>I would also like to know how to "carry over" the state of a variable from successive function calls, without having to define a global variable. Help please!</p>

<p>You need a base case  where times is 0, there you can just return an empty list:</p>

<pre><code>def func(times, data):
    if times == 0:
        return []
    # no need for split, just wrap data in a list.
    return [data] + func(times-1, data)
</code></pre>

<p>In your code when times == 0, your function implicitly returns None so you are trying to add the result of the recursive calls to None. We should also probably use &lt;= in the base case to catch negative input for times:</p>

<pre><code>def func(times, data):
    if times &lt;= 0:
        return []
    return [data] + func(times-1, data)
</code></pre>

<p>If we don't we would recurse infinitely and hit a <code>RuntimeError: maximum recursion depth exceeded</code> as we would never hit the base case.</p>

<p>There is a nice online tool <a href="http://www.pythontutor.com/visualize.html#" rel="nofollow">python tutor</a> that can visualise the steps so you can see exactly what is happening which would highlight why and where your code erros. </p>

<p>When you have a working solution  you could use <a href="https://github.com/carlsborg/rcviz" rel="nofollow">rcviz</a> which will create a nice png of the execution steps:</p>

<p><a href="http://i.stack.imgur.com/CNJaM.png" rel="nofollow"><img src="http://i.stack.imgur.com/CNJaM.png" alt="enter image description here"></a></p>

<p><em>Note: 1. The edges are numbered by the order in which they were traversed by the execution. 2. The edges are colored from black to grey to indicate order of traversal : black edges first, grey edge</em>s last.</p>

python