How to use recursion in python
<p>I am trying to solve a problem which stimulate movements of a robot. The robot starts with position (0, 0, 'N'). The command is given in a list of strings. the 'turn' function turns from N to E to S to W and back to N. The move function moves in the specific direction: N,S in y axis and E,W in x axis. N: y+1 S: y-1 W: x-1 E: x+1</p>

<p>The part I am having trouble with is, when trying to use shortcuts in the function. Using 'turnleft' instead of ['turn', 'turn', 'turn'], 'turnright' instead of 'turn'</p>

<pre><code>def macro_interpreter(code, macros):
</code></pre>

<p>when call the function:</p>

<pre><code>print(macro_interpreter(['turnleft', 'turnright'], {'turnleft': ['turn', 'turn', 'turn'], 'turnright' : ['turn'], 'bigleftturn' : ['move', 'move', 'turnleft', 'move', 'move'], 'bigrightturn' : ['move', 'move', 'turnright', 'move', 'move']}))
</code></pre>

<p>the definition of the term is given in a dictionary.
My code only runs for the first command and then terminate, it ignores the second code in the list</p>

<pre><code>def macro_interpreter(code, macros):
    x,y,index = 0, 0, 0
    state = ['N', 'E', 'S', 'W']
    for command in code:
        if command in macros:
            return macro_interpreter(macros[command], macros)
        else:
            if command == 'move':
                if state[index] == 'N':
                    y += 1
                elif state[index] == 'E':
                    x += 1
                elif state[index] == 'S':
                    y -= 1
                elif state[index] == 'W':
                    x -= 1
            elif command == 'turn':
                try:
                    index = index + 1
                except IndexError:
                    index = 0
    return (x, y, state[index])            
</code></pre>

<p>I suspect it's because you return </p>

<pre><code>macro_interpreter(macros[command], macros)
</code></pre>

<p>This simply exits the function once the recursed code is run. You'll see if you change</p>

<pre><code>return macro_interpreter(macros[command], macros)
</code></pre>

<p>to</p>

<pre><code>print macro_interpreter(macros[command], macros)
</code></pre>

<p>that the code will print what you want it to do. How you want to actually handle the output is up to you.</p>

python python-3.x