title: "Not in function" error in recursive function
body: <p>I'm writing an algorithm to count the total amount of nodes a tree has. This is the code:</p>
  
  <pre><code>def tree_nodes(tree):
      """Given a tree, returns the total amount of nodes it has."""
      def recursive_node_count(node):
          """Recursive count function."""
          childs = tree[node]
          if childs == None:
              return 1
          else:
              nodes_so_far = 0
              for i in xrange(len(childs)):
                  nodes_in_this_branch = recursive_node_count(childs[i])
                  nodes_so_far += nodes_in_this_branch          
              return nodes_so_far
  
      root = tree['root']
      total_nodes = recursive_node_count(root)
      return total_nodes
  </code></pre>
  
  <p>The <code>tree</code> is basically a dictionary of lists. Example:</p>
  
  <pre><code>tree = {0: [1], 1: [2], 2: [3, 4], 3: None, 4: None, 'root': 0}
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/UIGSS.png" alt="enter image description here"></p>
  
  <p>When I try to run my code, this is the output I receive:</p>
  
  <pre><code>at Answer.py. not in a function on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in recursive_node_count on line 31
  at Answer.py. in tree_nodes on line 36
  at Answer.py. in &lt;module&gt; on line 96
  </code></pre>
  
  <p>These are the lines <code>31</code> (inside the function definition), <code>36</code> (inside the definition too) and <code>96</code> (a call to the definition) in the original code:</p>
  
  <pre><code>31: nodes_in_this_branch = recursive_node_count(childs[i])
  36: total_nodes = recursive_node_count(root)
  96: nodes = tree_nodes(tree)
  </code></pre>
  
  <p>I checked the syntax, indentation, tabs, white spaces, but I can't find the error. I'm a beginner in Python. Could you guys please help me?</p>